import { pikkuSessionlessFunc } from '#pikku/pikku-types.gen.js'
import { sql } from 'kysely'
import { CountriesMap } from '@heygermany/sdk'

const localeToColumn: Record<string, string> = {
  'en': 'name',
  'de': 'name_de',
  'es': 'name_es',
  'fr': 'name_fr',
  'it': 'name_it',
  'pl': 'name_pl',
  'pt': 'name_pt',
  'ru': 'name_ru',
  'uk': 'name_uk',
  'tr': 'name_tr',
  'ja': 'name_ja',
  'ko': 'name_ko',
  'nl': 'name_nl',
  'hr': 'name_hr',
  'fa': 'name_fa',
}

export const getCountries = pikkuSessionlessFunc<
  { locale?: string },
  CountriesMap
>({
  auth: false,
  title: 'Get countries list',
  description: 'Returns countries map with ISO3 codes as keys and localized names as values',
  func: async ({ kysely }, { locale }) => {
    const column = localeToColumn[locale || 'en'] || 'name'

    const results = await kysely
      .selectFrom('countries')
      .select([
        'iso3',
        sql`COALESCE(${sql.ref(column)}, name)`.as('name')
      ])
      .orderBy(sql`COALESCE(${sql.ref(column)}, name)`, 'asc')
      .execute()

    return results.reduce((acc, row) => {
      acc[row.iso3] = row.name as string
      return acc
    }, {} as CountriesMap)
  }
})
