/**
 * Agent chat languages (Task 8 set; Task 71 per-profile selection).
 *
 * Nash, 2026-09-07: "I think we should have one language, English, first, and
 * then a button to add new language… choose any of the other three that you
 * want to add… It should stick to your profile… maybe you want to set one of
 * them to be primary language. The default language."
 *
 * The four launch languages are a prior decision and do not grow here.
 */

export const CHAT_LANGUAGES = [
  { code: 'en', label: '🇺🇸 English', name: 'English' },
  { code: 'es', label: '🇪🇸 Español', name: 'Spanish' },
  { code: 'ru', label: '🇷🇺 Русский', name: 'Russian' },
  { code: 'ro', label: '🇷🇴 Română', name: 'Romanian' },
] as const

export type ChatLanguageCode = (typeof CHAT_LANGUAGES)[number]['code']

export const LANGUAGE_CODES: string[] = CHAT_LANGUAGES.map((l) => l.code)

export const DEFAULT_LANGUAGE = 'en'

export function isLanguageCode(code: unknown): code is ChatLanguageCode {
  return typeof code === 'string' && LANGUAGE_CODES.includes(code)
}

export interface LanguagePrefs {
  /** Enabled languages, in the order they were added. Never empty. */
  languages: string[]
  /** The language every chat opens in. Always one of `languages`. */
  primary: string
}

/**
 * Normalise what the profile row holds into something the UI can trust:
 * unknown codes dropped, duplicates removed, never empty, primary always
 * enabled. Missing columns (migration 0011 not applied) read as English only.
 */
export function resolveLanguagePrefs(
  profile: { chat_languages?: string[] | null; primary_language?: string | null } | null | undefined,
): LanguagePrefs {
  const raw = Array.isArray(profile?.chat_languages) ? profile!.chat_languages! : []
  const languages = [...new Set(raw.filter(isLanguageCode))]
  if (languages.length === 0) languages.push(DEFAULT_LANGUAGE)
  const wanted = profile?.primary_language
  const primary = isLanguageCode(wanted) && languages.includes(wanted) ? wanted : languages[0]
  return { languages, primary }
}
