export const CHILD_MAX_AGE_YEARS = 7;

export function formatDateInputValue(date: Date) {
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, "0");
  const day = String(date.getDate()).padStart(2, "0");

  return `${year}-${month}-${day}`;
}

export function getChildBirthdateRange(referenceDate = new Date()) {
  const max = new Date(
    referenceDate.getFullYear(),
    referenceDate.getMonth(),
    referenceDate.getDate(),
  );
  const min = new Date(max);
  min.setFullYear(min.getFullYear() - CHILD_MAX_AGE_YEARS);

  return {
    min: formatDateInputValue(min),
    max: formatDateInputValue(max),
  };
}

export function parseDateInput(value?: string) {
  if (!value) return null;
  if (!/^\d{4}-\d{2}-\d{2}$/.test(value)) return null;

  const date = new Date(`${value}T00:00:00`);
  if (Number.isNaN(date.getTime())) return null;

  return formatDateInputValue(date) === value ? date : null;
}
