export function validateBirthdate(value?: string) {
  if (!value) return "";

  const birthdate = new Date(value);
  const today = new Date();

  today.setHours(0, 0, 0, 0);

  if (birthdate > today) {
    return "La date de naissance ne peut pas être postérieure à aujourd'hui.";
  }

  return "";
}

export function validateDateCreationCompany(value?: string) {
  if (!value) return "";

  const creationDate = new Date(value);
  const today = new Date();

  today.setHours(0, 0, 0, 0);

  if (creationDate > today) {
    return "La date de création ne peut pas être postérieure à aujourd'hui.";
  }

  return "";
}

export function calculateAge(birthdate: string) {
  if (!birthdate) return null;

  const today = new Date();
  const birth = new Date(birthdate);

  let age = today.getFullYear() - birth.getFullYear();
  const monthDiff = today.getMonth() - birth.getMonth();

  if (monthDiff < 0 || (monthDiff === 0 && today.getDate() < birth.getDate())) {
    age--;
  }

  return age;
}

function getNestedValue(obj: any, path: string) {
  return path.split(".").reduce((acc, key) => acc?.[key], obj);
}

export function getMissingRequiredFields(formData: Record<string, any>, requiredFields: string[]) {
  return requiredFields.filter((field) => {
    const value = getNestedValue(formData, field);

    return (value === undefined || value === null || value === "");
  });
}

export function getDateError(debut: string, fin: string) {
  if (!debut || !fin) return null;

  const d1 = new Date(debut);
  const d2 = new Date(fin);

  if (d1 > d2) {
    return "La date de début doit être antérieure à la date de fin";
  }

  return null;
}

export function computeDuree(debut: string, fin: string) {
  if (!debut || !fin) return 0;
  const d1 = new Date(debut);
  const d2 = new Date(fin);
  const diff = (d2.getTime() - d1.getTime()) / (1000 * 60 * 60 * 24 * 30); // mois approximatif
  return diff > 0 ? parseFloat(diff.toFixed(1)) : 0;
}

export function formatDuree(mois: number): string {
  if (mois >= 12) {
    const annees = mois / 12;

    // si entier → "2 ans"
    if (Number.isInteger(annees)) {
      return `${annees} an${annees > 1 ? "s" : ""}`;
    }

    // sinon → "1.5 ans"
    return `${annees.toFixed(1)} ans`;
  }

  return '';
}