import { eq } from "drizzle-orm";
import { schema } from "@app/database";
import { DEFAULT_LOCALE_PREFERENCES, toLocaleContext, type LocaleContext } from "@app/shared-types";
import type { WorkerContext } from "./context.js";

/** LocaleContext för AAMOS-anrop i workern (i18n-spec §22). SE-defaults som fallback. */
export async function getLocaleContext(
  ctx: WorkerContext,
  userId: string | null | undefined,
): Promise<LocaleContext> {
  if (!userId) return toLocaleContext(DEFAULT_LOCALE_PREFERENCES);
  const [row] = await ctx.db
    .select()
    .from(schema.userLocalePreferences)
    .where(eq(schema.userLocalePreferences.userId, userId))
    .limit(1);
  if (!row) return toLocaleContext(DEFAULT_LOCALE_PREFERENCES);
  return {
    languageTag: row.languageTag,
    regionCode: row.regionCode,
    timeZone: row.timeZone,
    measurementSystem: row.measurementSystem,
    temperatureUnit: row.temperatureUnit,
    currencyCode: row.currencyCode,
  };
}
