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;
  nationality: string;
  regionId?: string;
  cityId?: string;
  subCityId?: string;
  /** Legacy spelling still accepted by the address upsert endpoint. */
  subcityId?: string;
  woredaId?: string;
  kebeleId?: string;
  streetAddress?: string;
  primaryPhoneNumber: string;
  secondaryPhoneNumber?: string;
  email?: string;
  website: null;
  postalAddress?: string;
  emergencyContactName?: string;
  emergencyContactPhone?: string;
  emergencyContactRelation?: string;
}

/** Blank optional strings drop out; `kebeleId` always mirrors `woredaId`. */
export function toAddressPayload(values: AddressValues): AddressPayload {
  const clean = (v?: string) => (v && v.trim() ? v.trim() : undefined);
  const regionId = clean(values.regionId);
  // The location service uses the selected City for the profile's region.
  // Send that same id as cityId too, because profile completeness requires
  // both fields even when the location tree has no separate region node.
  const cityId = clean(values.cityId) ?? regionId;
  const subCityId = clean(values.subCityId);

  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,
    subcityId: subCityId, // legacy spelling, same value
    woredaId: clean(values.woredaId),
    kebeleId: clean(values.woredaId), // no separate Kebele field — mirrors woredaId
    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),
  };
}
