import { formatInTimeZone } from 'date-fns-tz';
import { getUtcStartEndOfDate } from './helpers';

export type DayClassification = 'weekend' | 'holiday' | 'working_day';

type HolidayLike = {
  departments?: Array<{ id: string }>;
};

export function classifyCalendarDay(
  member: { department_id?: string | null },
  requestDate: Date,
  timeZone: string,
  working_days: string[] | null | undefined,
  holidays: HolidayLike[],
): DayClassification {
  const { startUtc } = getUtcStartEndOfDate(requestDate, timeZone);
  const isHoliday = holidays.some((holiday) => {
    if (!holiday.departments?.length) return true;
    return holiday.departments.some((d) => d.id === member.department_id);
  });

  if (isHoliday) {
    return 'holiday';
  }

  const weekDay = formatInTimeZone(startUtc, timeZone, 'EEEE').toLowerCase();
  const isWeekend =
    !!working_days &&
    Array.isArray(working_days) &&
    working_days.length > 0 &&
    !working_days.includes(weekDay);

  return isWeekend ? 'weekend' : 'working_day';
}

export function isOffDayClassification(
  classification: DayClassification,
): boolean {
  return classification === 'weekend' || classification === 'holiday';
}
