import { eq } from "drizzle-orm";
import { schema, type Database } from "@app/database";
import {
  DEFAULT_LOCALE_PREFERENCES,
  toLocaleContext,
  type LocaleContext,
  type UserLocalePreferences,
} from "@app/shared-types";

/** Läs användarens locale-preferenser med SE-defaults som fallback (i18n-spec §6). */
export async function loadLocalePreferences(
  db: Database,
  userId: string,
): Promise<UserLocalePreferences> {
  const [row] = await db
    .select()
    .from(schema.userLocalePreferences)
    .where(eq(schema.userLocalePreferences.userId, userId))
    .limit(1);
  if (!row) return { ...DEFAULT_LOCALE_PREFERENCES };
  return {
    languageTag: row.languageTag,
    regionCode: row.regionCode,
    timeZone: row.timeZone,
    measurementSystem: row.measurementSystem,
    temperatureUnit: row.temperatureUnit,
    currencyCode: row.currencyCode,
    firstDayOfWeek: row.firstDayOfWeek,
    use24HourTime: row.use24HourTime,
  };
}

/** LocaleContext till varje AAMOS-anrop (i18n-spec §22). */
export async function getLocaleContext(db: Database, userId: string): Promise<LocaleContext> {
  return toLocaleContext(await loadLocalePreferences(db, userId));
}
