"use server";

// Server action: update the signed-in user's preferred locale.
//
// Persistence: admin.users.locale (single source of truth) — keyed by
// gscSID, so any other app that does a one-time DB lookup on signin
// can pick it up. Per the gsc-identity-boundaries memory, `locale`
// is one of the explicitly-allowed app-local preference columns.
//
// Immediate cross-app effect: NEXT_LOCALE cookie set with
// Domain=.gosec.internal so admin.gosec.internal, my.gosec.internal,
// and any sibling host pick up the new locale on the next request
// without needing a fresh signin or DB round-trip.

import { auth } from "@/auth";
import { prisma } from "@/database/prisma";
import { cookies } from "next/headers";
import { revalidatePath } from "next/cache";

const ALLOWED_LOCALES = ["en", "de", "fr"] as const;
type AllowedLocale = (typeof ALLOWED_LOCALES)[number];

function isAllowed(v: string): v is AllowedLocale {
  return (ALLOWED_LOCALES as readonly string[]).includes(v);
}

const COOKIE_NAME = "NEXT_LOCALE";
const COOKIE_DOMAIN = ".gosec.internal";
const ONE_YEAR_SECONDS = 60 * 60 * 24 * 365;

export async function setLocale(newLocale: string): Promise<{ ok: boolean; error?: string }> {
  if (!isAllowed(newLocale)) {
    return { ok: false, error: "unsupported_locale" };
  }
  const session = await auth();
  const user = session?.user as { gscSid?: string; email?: string } | undefined;
  const gscsid = user?.gscSid;
  if (!gscsid) return { ok: false, error: "unauthorized" };

  // Persist. Upsert so a user who's never had a row gets one.
  await prisma.user.upsert({
    where: { gscsid },
    update: { locale: newLocale },
    create: {
      gscsid,
      locale: newLocale,
      status: "active",
      email: user.email ?? null,
    },
  });

  // Cross-app effect: cookie on the parent domain.
  const c = await cookies();
  c.set({
    name: COOKIE_NAME,
    value: newLocale,
    domain: COOKIE_DOMAIN,
    path: "/",
    sameSite: "lax",
    secure: true,
    httpOnly: false,        // read by next-intl on the server; not sensitive
    maxAge: ONE_YEAR_SECONDS,
  });

  revalidatePath("/settings");
  return { ok: true };
}
