export type Schedule = 'monthly' | 'weekly' | 'biweekly' | 'quarterly' | 'annual';

export const BILLING_SCHEDULE_OPTIONS: [Schedule, string][] = [
  ['monthly', 'Monthly'],
  ['weekly', 'Weekly'],
  ['biweekly', 'Biweekly'],
  ['quarterly', 'Quarterly'],
  ['annual', 'Annual'],
];

const LABELS: Record<string, string> = Object.fromEntries(BILLING_SCHEDULE_OPTIONS);

export interface ScheduleBill {
  cycle_type?: string | null;
  billing_cycle?: string | null;
}

export function scheduleFromBillingCycle(billingCycle: string | null | undefined): Schedule {
  const value = String(billingCycle || '').toLowerCase();
  if (value === 'quarterly') return 'quarterly';
  if (value === 'annually' || value === 'annual') return 'annual';
  return 'monthly';
}

export function normalizeSchedule(value: string | null | undefined, fallback = 'monthly'): string {
  if (!value) return fallback;
  const normalized = String(value).toLowerCase();
  return LABELS[normalized] ? normalized : fallback;
}

export function scheduleValue(bill: ScheduleBill = {}): string {
  const cycleType = normalizeSchedule(bill.cycle_type, '');
  const billingCycle = String(bill.billing_cycle || '').toLowerCase();

  if (cycleType === 'monthly' && ['quarterly', 'annually', 'annual'].includes(billingCycle)) {
    return scheduleFromBillingCycle(billingCycle);
  }

  return cycleType || scheduleFromBillingCycle(billingCycle);
}

export function scheduleLabel(valueOrBill: string | ScheduleBill | null | undefined): string {
  const value = valueOrBill && typeof valueOrBill === 'object'
    ? scheduleValue(valueOrBill)
    : normalizeSchedule(valueOrBill);
  return LABELS[value] || 'Monthly';
}

export function billingCycleForSchedule(schedule: string | null | undefined): string {
  const value = normalizeSchedule(schedule);
  if (value === 'quarterly') return 'quarterly';
  if (value === 'annual') return 'annually';
  if (value === 'weekly' || value === 'biweekly') return 'irregular';
  return 'monthly';
}

export function defaultCycleDayForSchedule(schedule: string | null | undefined): string {
  const value = normalizeSchedule(schedule);
  return value === 'weekly' || value === 'biweekly' ? 'monday' : '1';
}
