import { auth } from "@/auth";
import { prisma } from "@/database/prisma";
import { getLocale } from "next-intl/server";
import LanguageForm from "./LanguageForm";

export const dynamic = "force-dynamic";

export const metadata = { title: "Settings — GSC My" };

export default async function SettingsPage() {
  // Prefer the persisted preference; fall back to whatever next-intl
  // resolved for this request (cookie / Accept-Language / default).
  const session = await auth();
  const gscsid = (session?.user as { gscSid?: string } | undefined)?.gscSid;
  let stored: string | null = null;
  if (gscsid) {
    try {
      const row = await prisma.user.findUnique({
        where: { gscsid },
        select: { locale: true },
      });
      stored = row?.locale ?? null;
    } catch (err) {
      console.warn("[settings] locale lookup failed:", err);
    }
  }
  const initial = stored ?? (await getLocale());

  return (
    <div className="container py-4">
      <h2 className="mb-4">
        <i className="ph ph-gear me-2" aria-hidden="true"></i>
        Settings
      </h2>
      <LanguageForm initialLocale={initial} />
    </div>
  );
}
