/** Helpers for "YYYY-MM" billing periods, computed in UTC to avoid tz drift. */

export function isValidPeriod(period: string): boolean {
  return /^\d{4}-(0[1-9]|1[0-2])$/.test(period);
}

export interface MonthRange {
  start: Date; // 1st, 00:00:00 UTC
  end: Date; // last day, 23:59:59.999 UTC
  daysInMonth: number;
  year: number;
  month: number; // 1–12
}

export function monthRange(period: string): MonthRange {
  const [y, m] = period.split('-').map(Number);
  const start = new Date(Date.UTC(y, m - 1, 1, 0, 0, 0, 0));
  const daysInMonth = new Date(Date.UTC(y, m, 0)).getUTCDate();
  const end = new Date(Date.UTC(y, m - 1, daysInMonth, 23, 59, 59, 999));
  return { start, end, daysInMonth, year: y, month: m };
}

/** Months since year 0, for comparing and stepping "YYYY-MM" periods. */
export function periodIndex(period: string): number {
  const [y, m] = period.split('-').map(Number);
  return y * 12 + (m - 1);
}

/** `period` moved forward by `months` (negative steps back). */
export function addMonths(period: string, months: number): string {
  const idx = periodIndex(period) + months;
  const y = Math.floor(idx / 12);
  const m = (idx % 12) + 1;
  return `${y}-${String(m).padStart(2, '0')}`;
}

/** The last month an invoice starting at `period` and spanning `cycleMonths` covers. */
export function periodEnd(period: string, cycleMonths: number): string {
  return addMonths(period, Math.max(1, cycleMonths) - 1);
}

/** A due date within the period, clamped to a safe day (1–28). */
export function dueDateFor(period: string, day: number): Date {
  const { year, month } = monthRange(period);
  const safeDay = Math.min(Math.max(day, 1), 28);
  return new Date(Date.UTC(year, month - 1, safeDay, 0, 0, 0, 0));
}
