/**
 * Vacation utility functions for the engine layer.
 * These are pure functions — no DB imports.
 */

export interface VacationRange {
  startDate: Date;
  endDate: Date;
  status: string;
}

/**
 * Returns true if the given date falls within any APPROVED vacation range.
 */
export function isVacationDay(date: Date, vacations: VacationRange[]): boolean {
  const t = new Date(date);
  t.setHours(0, 0, 0, 0);
  const time = t.getTime();

  for (const v of vacations) {
    if (v.status !== "APPROVED") continue;
    const start = new Date(v.startDate);
    start.setHours(0, 0, 0, 0);
    const end = new Date(v.endDate);
    end.setHours(0, 0, 0, 0);
    if (time >= start.getTime() && time <= end.getTime()) return true;
  }
  return false;
}

/**
 * Returns all APPROVED vacation dates (as Date objects) that fall within [startDate, endDate].
 * Used for demand recalculation display.
 */
export function getVacationDatesInRange(
  startDate: Date,
  endDate: Date,
  vacations: VacationRange[],
): Date[] {
  const result: Date[] = [];
  const approved = vacations.filter((v) => v.status === "APPROVED");

  const current = new Date(startDate);
  current.setHours(0, 0, 0, 0);
  const end = new Date(endDate);
  end.setHours(0, 0, 0, 0);

  while (current <= end) {
    for (const v of approved) {
      const vStart = new Date(v.startDate);
      vStart.setHours(0, 0, 0, 0);
      const vEnd = new Date(v.endDate);
      vEnd.setHours(0, 0, 0, 0);
      if (current >= vStart && current <= vEnd) {
        result.push(new Date(current));
        break;
      }
    }
    current.setDate(current.getDate() + 1);
  }

  return result;
}
