import 'server-only'

import { cache } from 'react'
import { cookies } from 'next/headers'

import ar from '@/messages/ar.json'
import en from '@/messages/en.json'

import { DEFAULT_LOCALE, LOCALE_COOKIE, dirFor, isLocale, type Locale } from './config'
import { createTranslator, type Messages, type Translator } from './translate'

const DICTIONARIES: Record<Locale, Messages> = {
  ar: ar as Messages,
  en: en as Messages,
}

export function getMessages(locale: Locale): Messages {
  return DICTIONARIES[locale]
}

/**
 * Resolves the active locale from the cookie the language switcher writes.
 *
 * Deliberately cookie-only: the root layout runs on every request and must not need a
 * database round-trip to decide which direction to render. The user's stored preference
 * is written into this cookie at sign-in, so the two stay in step.
 */
export const getLocale = cache(async (): Promise<Locale> => {
  const store = await cookies()
  const value = store.get(LOCALE_COOKIE)?.value
  return isLocale(value) ? value : DEFAULT_LOCALE
})

export interface ServerI18n {
  locale: Locale
  dir: 'rtl' | 'ltr'
  messages: Messages
  t: Translator
}

export const getI18n = cache(async (): Promise<ServerI18n> => {
  const locale = await getLocale()
  const messages = getMessages(locale)
  return { locale, dir: dirFor(locale), messages, t: createTranslator(messages) }
})

/** Picks the field matching the active locale from a bilingual record. */
export function localised<T extends Record<string, unknown>>(
  row: T,
  base: string,
  locale: Locale,
): string {
  const key = locale === 'ar' ? `${base}Ar` : base
  const value = row[key] ?? row[base]
  return typeof value === 'string' ? value : ''
}
