export type Coverage = {
  required: number;
  covered: number;
  remaining: number;
  percentage: number;
};

export function calculateAge(dateOfBirth: string | Date | null | undefined, today = new Date()): number | null {
  if (!dateOfBirth) return null;
  const birth = typeof dateOfBirth === "string" ? new Date(`${dateOfBirth}T00:00:00`) : dateOfBirth;
  if (Number.isNaN(birth.getTime()) || birth > today) return null;

  let age = today.getFullYear() - birth.getFullYear();
  const monthDifference = today.getMonth() - birth.getMonth();
  if (monthDifference < 0 || (monthDifference === 0 && today.getDate() < birth.getDate())) age -= 1;
  return Math.max(0, age);
}

export function calculateCoverage(required: number, contributions: number[]): Coverage {
  const safeRequired = Math.max(0, required);
  const covered = Math.max(0, contributions.reduce((sum, value) => sum + Math.max(0, value), 0));
  const remaining = Math.max(0, safeRequired - covered);
  const percentage = safeRequired === 0 ? 100 : Math.min(100, Math.round((covered / safeRequired) * 100));
  return { required: safeRequired, covered, remaining, percentage };
}

export function paymentStatus(required: number, paid: number): "unpaid" | "partial" | "paid" {
  if (paid <= 0) return "unpaid";
  if (paid < required) return "partial";
  return "paid";
}

export function formatSdg(value: number): string {
  return `${new Intl.NumberFormat("ar-SD", { maximumFractionDigits: 0 }).format(value)} ج.س`;
}

export function monthKey(date = new Date()): string {
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}`;
}
