import { getCountryName } from '@ema-platform/ui';
import type { AddressValues } from '../components/AddressFormContent';

/** Exact request body of `POST /addresss/profile/{profileId}`. */
export interface AddressPayload {
  idType: string;
  idNumber: string;
  passportNumber?: string;
  passportExpiry?: string;
  nationality: string;
  regionId?: string;
  cityId?: string;
  subCityId?: string;
  woredaId?: string;
  kebeleId?: string;
  streetAddress?: string;
  /** Where the seafarer currently lives, when different from the address above. */
  currentAddress?: string;
  primaryPhoneNumber: string;
  secondaryPhoneNumber?: string;
  email?: string;
  website: null;
  postalAddress?: string;
  emergencyContactName?: string;
  emergencyContactPhone?: string;
  emergencyContactRelation?: string;
}

/** Blank optional strings drop out. */
export function toAddressPayload(values: AddressValues): AddressPayload {
  const clean = (v?: string) => (v && v.trim() ? v.trim() : undefined);
  const regionId = clean(values.regionId);
  // The seeded location tree tops out at CITY — Addis Ababa is a city-state,
  // so a selected city stands in for the region and both ids are the same
  // node. Profile completeness requires both, and the picker only ever yields
  // one of them.
  const cityId = clean(values.cityId) ?? regionId;

  return {
    idType: values.idType.trim(),
    idNumber: values.idNumber.trim(),
    // Form holds the alpha-2 code (CountrySelect); API stores the full name.
    nationality: getCountryName(values.nationality),
    regionId,
    cityId,
    subCityId: clean(values.subCityId),
    woredaId: clean(values.woredaId),
    // Left unset rather than mirroring woredaId: the picker stops at woreda,
    // and copying that id here filed a WOREDA-typed node in kebele_id, so the
    // column could not be trusted to mean what it says.
    kebeleId: clean(values.kebeleId),
    streetAddress: clean(values.streetAddress),
    primaryPhoneNumber: values.primaryPhoneNumber,
    secondaryPhoneNumber: clean(values.secondaryPhoneNumber),
    email: clean(values.email),
    website: null, // no website field in the form — always sent as null
    postalAddress: clean(values.postalAddress),
    emergencyContactName: clean(values.emergencyContactName),
    emergencyContactPhone: clean(values.emergencyContactPhone),
    emergencyContactRelation: clean(values.emergencyContactRelation),
  };
}
