import { filterAutoCompleteLocations } from "./filterAutoCompleteLocations"

import type { AutoCompleteLocation } from "../schema"

export type DestinationsAutoCompleteOutput = {
  hits: {
    hotels: AutoCompleteLocation[]
    cities: AutoCompleteLocation[]
    countries: AutoCompleteLocation[]
  }
  currentSelection: {
    hotel: (AutoCompleteLocation & { type: "hotels" }) | null
    city: (AutoCompleteLocation & { type: "cities" }) | null
  }
}

export function filterAndCategorizeAutoComplete({
  locations,
  query,
  includeTypes,
}: {
  locations: AutoCompleteLocation[]
  query: string
  includeTypes: ("cities" | "hotels" | "countries")[]
}) {
  const rankedLocations = filterAutoCompleteLocations(locations, query)

  const sortedCities = rankedLocations.filter(
    (loc) => shouldIncludeType(includeTypes, loc) && isCity(loc)
  )
  const sortedHotels = rankedLocations.filter(
    (loc) => shouldIncludeType(includeTypes, loc) && isHotel(loc)
  )
  const sortedCountries = rankedLocations.filter(
    (loc) => shouldIncludeType(includeTypes, loc) && isCountry(loc)
  )

  return {
    cities: sortedCities,
    hotels: sortedHotels,
    countries: sortedCountries,
  }
}

function shouldIncludeType(
  includedTypes: ("cities" | "hotels" | "countries")[],
  location: AutoCompleteLocation
) {
  return includedTypes.includes(location.type)
}

function isHotel(
  location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "hotels" } {
  return !!location && location.type === "hotels"
}

function isCountry(
  location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "countries" } {
  return !!location && location.type === "countries"
}

function isCity(
  location: AutoCompleteLocation | null | undefined
): location is AutoCompleteLocation & { type: "cities" } {
  return !!location && location.type === "cities"
}
