package com.storlead.sales.task.broadcast;

import com.storlead.sales.service.customer.StorleadCalendarService;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.TemporalAdjusters;

/**
 * 周、月、季度、半年、年度首个工作日判定工具（依赖日历服务）。
 */
final class FirstMondayChecker {

    private FirstMondayChecker() {
    }

    /**
     * 是否为当周的首个工作日（用于周报触发）。
     */
    static boolean isWeek(LocalDate date, StorleadCalendarService calendarService) {
        LocalDate start = date.with(TemporalAdjusters.previousOrSame(DayOfWeek.MONDAY));
        LocalDate firstWorkday = firstWorkdayFrom(start, calendarService, 7);
        return date.equals(firstWorkday);
//        return true;
    }

    /**
     * 是否为当月首个工作日（用于月报触发）。
     */
    static boolean isMonth(LocalDate date, StorleadCalendarService calendarService) {
        LocalDate firstDay = date.with(TemporalAdjusters.firstDayOfMonth());
        LocalDate firstWorkday = firstWorkdayFrom(firstDay, calendarService, 31);
        return date.equals(firstWorkday);
//        return true;
    }

    /**
     * 是否为当季度首月的首个工作日（用于季报触发）。
     */
    static boolean isQuarter(LocalDate date, StorleadCalendarService calendarService) {
        Month firstMonthOfQuarter = date.getMonth().firstMonthOfQuarter();
        LocalDate firstMonthDate = LocalDate.of(date.getYear(), firstMonthOfQuarter, 1);
        LocalDate firstWorkday = firstWorkdayFrom(firstMonthDate, calendarService, 35);
        return date.equals(firstWorkday);
//        return true;
    }

    /**
     * 是否为当半年度首月（1/7月）的首个工作日（用于半年报触发）。
     */
    static boolean isHalfYear(LocalDate date, StorleadCalendarService calendarService) {
        Month startMonth = date.getMonthValue() <= Month.JUNE.getValue() ? Month.JANUARY : Month.JULY;
        LocalDate startDate = LocalDate.of(date.getYear(), startMonth, 1);
        LocalDate firstWorkday = firstWorkdayFrom(startDate, calendarService, 31);
        return date.equals(firstWorkday);
//        return true;
    }

    /**
     * 是否为当年首月（1月）的首个工作日（用于年报触发）。
     */
    static boolean isYear(LocalDate date, StorleadCalendarService calendarService) {
        LocalDate startDate = LocalDate.of(date.getYear(), Month.JANUARY, 1);
        LocalDate firstWorkday = firstWorkdayFrom(startDate, calendarService, 31);
        return date.equals(firstWorkday);
//        return true;
    }

    /**
     * 从 start 起向后查找首个工作日，最多检查 maxDays（防止配置缺失导致死循环）。
     */
    private static LocalDate firstWorkdayFrom(LocalDate start, StorleadCalendarService calendarService, int maxDays) {
        LocalDate d = start;
        for (int i = 0; i < maxDays; i++) {
            if (calendarService != null && calendarService.isWorkDay(d)) {
                return d;
            }
            d = d.plusDays(1);
        }
        return start; // 若未找到，降级为起始日
    }
}
