import { ConfigSingleton } from '../../config/ConfigSingleton';

export function toDateOnly(d: Date): string {
  return d.toISOString().slice(0, 10);
}

export function parseDateOnly(s: string): Date {
  return new Date(`${s}T00:00:00.000Z`);
}

export function addDays(dateStr: string, days: number): string {
  const d = parseDateOnly(dateStr);
  d.setUTCDate(d.getUTCDate() + days);
  return toDateOnly(d);
}

export function todayInCompanyTz(): string {
  const tz = ConfigSingleton.getInstance().companyTimezone;
  return new Intl.DateTimeFormat('en-CA', { timeZone: tz }).format(new Date());
}

export function nowInCompanyTz(): Date {
  return new Date();
}

export function getYearMonth(dateStr: string): string {
  return dateStr.slice(0, 7);
}

export function isWeekend(dateStr: string): boolean {
  const d = parseDateOnly(dateStr);
  const day = d.getUTCDay();
  return day === 0 || day === 6;
}

export function daysBetweenInclusive(start: string, end: string): string[] {
  const out: string[] = [];
  let cur = start;
  while (cur <= end) {
    out.push(cur);
    cur = addDays(cur, 1);
  }
  return out;
}

export function quarterKey(dateStr: string): string {
  const month = parseInt(dateStr.slice(5, 7), 10);
  const year = dateStr.slice(0, 4);
  const q = Math.ceil(month / 3);
  return `${year}-Q${q}`;
}

export function monthEndDate(yearMonth: string): string {
  const [y, m] = yearMonth.split('-').map(Number);
  const last = new Date(Date.UTC(y, m, 0));
  return toDateOnly(last);
}

export function daysUntilMonthEnd(fromDate: string): number {
  const ym = getYearMonth(fromDate);
  const end = monthEndDate(ym);
  const start = parseDateOnly(fromDate);
  const endD = parseDateOnly(end);
  return Math.round((endD.getTime() - start.getTime()) / 86400000);
}

export function nextMonth(yearMonth: string): string {
  const [y, m] = yearMonth.split('-').map(Number);
  const d = new Date(Date.UTC(m === 12 ? y + 1 : y, m === 12 ? 0 : m, 1));
  return `${d.getUTCFullYear()}-${String(d.getUTCMonth() + 1).padStart(2, '0')}`;
}
