/**
 * Days served on one engagement, counted inclusively — embarkation and
 * discharge days both count. The same arithmetic the API uses for approved
 * sea time (`SeafarerRecordService.approvedSeaTime`), so the figure a seafarer
 * sees while typing is the figure the eligibility gate will credit.
 *
 * `null` until both dates are set or while they are out of order.
 */
export function seaServiceDays(
  engagementDate: string | null | undefined,
  dischargeDate: string | null | undefined,
): number | null {
  if (!engagementDate || !dischargeDate) return null;
  const from = Date.UTC(...dateParts(engagementDate));
  const to = Date.UTC(...dateParts(dischargeDate));
  if (Number.isNaN(from) || Number.isNaN(to) || to < from) return null;
  return Math.round((to - from) / 86_400_000) + 1;
}

function dateParts(value: string): [number, number, number] {
  const [y, m, d] = value.slice(0, 10).split('-').map(Number);
  return [y, (m || 1) - 1, d || 1];
}
