import { addDays, type DateOnly } from "../../shared/dates.js";

export interface Schedule { id: string; anchor: string; openOffset: number; dueOffset: number; graceDays: number; repeatEvery: number | null; repeatCount: number | null; level: string | null; durationId: string | null; providerId: string | null }
export interface Window { seq: number; open: DateOnly; due: DateOnly; close: DateOnly }
/** The most specific schedule wins: provider, then duration, then level, then everyone. */
export function pickSchedule<S extends Schedule>(all: S[], t: { providerId: string; durationId: string | null; level: string | null }): S | undefined {
  const fits = all.filter((s) => (!s.providerId || s.providerId === t.providerId) && (!s.durationId || s.durationId === t.durationId) && (!s.level || s.level === t.level));
  const weight = (s: S) => (s.providerId ? 4 : 0) + (s.durationId ? 2 : 0) + (s.level ? 1 : 0);
  return fits.sort((a, b) => weight(b) - weight(a) || Number(b.id) - Number(a.id))[0];
}
/** Breakdown days move the due and closing dates by the same number of days. */
export function windows(s: Schedule, anchor: DateOnly, extraDays = 0): Window[] {
  return Array.from({ length: Math.max(1, s.repeatCount ?? 1) }, (_, i) => {
    const shift = i * (s.repeatEvery ?? 0), due = addDays(anchor, s.dueOffset + shift + extraDays);
    return { seq: i + 1, open: addDays(anchor, s.openOffset + shift), due, close: addDays(due, s.graceDays) };
  });
}
export const statusOn = (current: string, w: { open: DateOnly; due: DateOnly }, now: DateOnly): string => (["submitted", "approved", "waived", "returned"].includes(current) ? current : now < w.open ? "upcoming" : now > w.due ? "overdue" : "open");
