import 'server-only' import { cookies, headers } from 'next/headers' import { COUNTRIES } from './countries' import type { CurrentMember } from './member-auth' export const COUNTRY_COOKIE = 'lokiloto_country' export const DEFAULT_COUNTRY = 'CA-QC' function isKnown(code: string | null | undefined): code is string { return !!code && COUNTRIES.some((c) => c.code === code) } /** Cloudflare's CF-IPCountry is ISO alpha-2; Canada maps to Québec, the only Canadian locale so far. */ function fromGeo(iso: string | null): string | null { if (!iso) return null const code = iso.toUpperCase() === 'CA' ? 'CA-QC' : iso.toUpperCase() return isKnown(code) ? code : null } /** Saved choice (cookie, then member profile) beats geo-detection, which beats the default. */ export async function resolveCountry(member: CurrentMember | null): Promise { const jar = await cookies() const saved = jar.get(COUNTRY_COOKIE)?.value if (isKnown(saved)) return saved if (isKnown(member?.favoriteCountry)) return member.favoriteCountry const h = await headers() return fromGeo(h.get('cf-ipcountry')) ?? DEFAULT_COUNTRY } export function isKnownCountry(code: string): boolean { return isKnown(code) }