import { cookies, headers } from "next/headers";
import { I18N_CONFIG } from "./config";
import { auth } from "./auth";
import { queryOne } from "./db";
async function getUserLocale() {
  var _a, _b;
  try {
    const sessionHeaders = await headers();
    const session = await auth.api.getSession({ headers: sessionHeaders });
    if ((_a = session == null ? void 0 : session.user) == null ? void 0 : _a.id) {
      const user = await queryOne(
        'SELECT language FROM "users" WHERE id = $1',
        [session.user.id]
      );
      if ((user == null ? void 0 : user.language) && I18N_CONFIG.supportedLocales.includes(user.language)) {
        return user.language;
      }
    }
  } catch (error) {
  }
  try {
    const cookieStore = await cookies();
    const cookieLocale = (_b = cookieStore.get(I18N_CONFIG.cookie.name)) == null ? void 0 : _b.value;
    if (cookieLocale && I18N_CONFIG.supportedLocales.includes(cookieLocale)) {
      return cookieLocale;
    }
  } catch (error) {
  }
  try {
    const headersList = await headers();
    const acceptLanguage = headersList.get("accept-language");
    if (acceptLanguage) {
      const preferredLocale = acceptLanguage.split(",")[0].split("-")[0];
      if (I18N_CONFIG.supportedLocales.includes(preferredLocale)) {
        return preferredLocale;
      }
    }
  } catch (error) {
  }
  return I18N_CONFIG.defaultLocale;
}
async function setUserLocale(locale) {
  if (!I18N_CONFIG.supportedLocales.includes(locale)) {
    throw new Error(
      `Unsupported locale: ${locale}. Supported locales: ${I18N_CONFIG.supportedLocales.join(", ")}`
    );
  }
  const cookieStore = await cookies();
  const cookieConfig = I18N_CONFIG.cookie;
  cookieStore.set(cookieConfig.name, locale, {
    expires: new Date(Date.now() + cookieConfig.maxAge),
    httpOnly: cookieConfig.httpOnly,
    secure: cookieConfig.secure === "auto" ? process.env.NODE_ENV === "production" : cookieConfig.secure,
    sameSite: cookieConfig.sameSite,
    path: cookieConfig.path
  });
}
const SUPPORTED_LOCALES = I18N_CONFIG.supportedLocales;
export {
  SUPPORTED_LOCALES,
  getUserLocale,
  setUserLocale
};
