export type AddressSuggestion = {
  label: string;
  addressLine: string;
  postcode: string;
  city: string;
};

type AdresseApiFeature = {
  properties?: {
    label?: string;
    name?: string;
    housenumber?: string;
    street?: string;
    postcode?: string;
    city?: string;
  };
};

type AdresseApiResponse = {
  features?: AdresseApiFeature[];
};

function buildAddressLine(feature: AdresseApiFeature): string {
  const properties = feature.properties;
  const housenumber = properties?.housenumber?.trim();
  const street = properties?.street?.trim();
  const name = properties?.name?.trim();

  if (housenumber && street) {
    return `${housenumber} ${street}`;
  }

  return street || name || properties?.label?.trim() || "";
}

export function mapAdresseApiResponseToSuggestions(
  response: AdresseApiResponse
): AddressSuggestion[] {
  return (response.features || [])
    .map((feature) => {
      const properties = feature.properties;
      const label = properties?.label?.trim() || "";
      const addressLine = buildAddressLine(feature);
      const postcode = properties?.postcode?.trim() || "";
      const city = properties?.city?.trim() || "";

      if (!label || !addressLine || !postcode || !city) {
        return null;
      }

      return {
        label,
        addressLine,
        postcode,
        city,
      };
    })
    .filter((suggestion): suggestion is AddressSuggestion => Boolean(suggestion));
}

export async function fetchAddressSuggestions(
  query: string,
  signal?: AbortSignal
): Promise<AddressSuggestion[]> {
  const trimmedQuery = query.trim();

  if (trimmedQuery.length < 3) {
    return [];
  }

  const url = new URL("https://api-adresse.data.gouv.fr/search/");
  url.searchParams.set("q", trimmedQuery);
  url.searchParams.set("limit", "5");
  url.searchParams.set("autocomplete", "1");

  const response = await fetch(url.toString(), { signal });

  if (!response.ok) {
    throw new Error("Impossible de recuperer les suggestions d'adresse");
  }

  const json = (await response.json()) as AdresseApiResponse;
  return mapAdresseApiResponseToSuggestions(json);
}
