import { WorkSchedule } from '../../users/entities/user.entity';

const WORK_DAYS: Record<WorkSchedule, number[]> = {
  [WorkSchedule.FOUR_DAYS]:  [1, 2, 3, 4],
  [WorkSchedule.FIVE_DAYS]:  [1, 2, 3, 4, 5],
  [WorkSchedule.SIX_DAYS]:   [1, 2, 3, 4, 5, 6],
};

export function calculateWorkingDays(
  startDate: Date,
  endDate: Date,
  schedule: WorkSchedule,
  publicHolidays: Date[],
): number {
  const workDays = WORK_DAYS[schedule];

  const holidays = publicHolidays.map(d => {
    const date = d instanceof Date ? d : new Date(d);
    return date.toISOString().split('T')[0];
  });

  let count = 0;
  const current = new Date(startDate);
  const end = new Date(endDate);

  while (current <= end) {
    const dayOfWeek = current.getDay();
    const dateStr = current.toISOString().split('T')[0];

    if (workDays.includes(dayOfWeek) && !holidays.includes(dateStr)) {
      count++;
    }

    current.setDate(current.getDate() + 1);
  }

  return count;
}

export function calculateWithHalfDays(
  startDate: Date,
  endDate: Date,
  isHalfStart: boolean,
  isHalfEnd: boolean,
  schedule: WorkSchedule,
  publicHolidays: Date[],
): number {
  let days = calculateWorkingDays(startDate, endDate, schedule, publicHolidays);
  if (isHalfStart) days -= 0.5;
  if (isHalfEnd) days -= 0.5;
  return Math.max(days, 0.5);
}