import { Lang } from "@/constants/languages"
import {
  getCountries,
  getHotelIdsByCountry,
} from "@/server/routers/hotels/utils"
import { getServiceToken } from "@/server/tokenManager"

import { safeTry } from "@/utils/safeTry"

import type { WarmupFunction, WarmupResult } from "."

export const warmupHotelIdsByCountry =
  (): WarmupFunction => async (): Promise<WarmupResult> => {
    try {
      let serviceToken = await getServiceToken()

      const [countries, countriesError] = await safeTry(
        getCountries({
          lang: Lang.en,
          serviceToken: serviceToken.access_token,
          warmup: true,
        })
      )

      if (!countries || countriesError) {
        return {
          status: "error",
          error: new Error("Unable to get countries"),
        }
      }

      const countryNames = countries.data.map((country) => country.name)
      for (const countryName of countryNames) {
        serviceToken = await getServiceToken()
        const [_, error] = await safeTry(
          getHotelIdsByCountry({
            country: countryName,
            serviceToken: serviceToken.access_token,
          })
        )

        if (error) {
          console.error(
            `[Warmup]: Error fetching hotel IDs for ${countryName}:`,
            error
          )
          continue
        }
      }

      return {
        status: "completed",
      }
    } catch (error) {
      return {
        status: "error",
        error: error as Error,
      }
    }
  }
