"use server";

import { revalidatePath } from "next/cache";
import { cookies } from "next/headers";
import { auth } from "@/auth";
import { setUserPreferredLanguage, uidFromGscSid } from "@/lib/freeipa-ldap";

export interface ActionResult {
  success?: boolean;
  message?: string;
  error?: string;
}

// Locales the chrome ships translations for. Keep in sync with
// src/i18n/request.ts.
const ALLOWED_LOCALES = new Set(["en", "de", "fr"]);

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

/**
 * Save user account settings.
 *
 * v1 only persists the `language` field (FreeIPA `preferredLanguage`
 * attribute, written via the svc-gsc-admin LDAP bind). The other keys
 * the AccountSettings form posts (theme, notification toggles, calendar
 * prefs, …) used to land in `admin.user_settings` via the legacy
 * `gscUserId` path — that DB-shadow user table is being deprecated per
 * the gsc-identity-boundaries decision, so those settings are accepted
 * silently for now and a Phase-2 redesign will pick the durable store
 * for each one (probably FreeIPA user attributes too).
 */
export async function saveAccountSettings(data: Record<string, unknown>): Promise<ActionResult> {
  try {
    const session = await auth();
    const user = session?.user as { gscSid?: string } | undefined;
    const gscsid = user?.gscSid;
    if (!gscsid) {
      return { error: "Not signed in." };
    }

    const language = typeof data.language === "string" ? data.language : null;
    if (language) {
      if (!ALLOWED_LOCALES.has(language)) {
        return { error: `Unsupported language '${language}'.` };
      }
      const uid = uidFromGscSid(gscsid);
      await setUserPreferredLanguage(uid, language);

      // Immediate cross-app effect — Keycloak claim won't refresh
      // until next token refresh, but every *.gosec.internal app's
      // i18n/request.ts reads NEXT_LOCALE first.
      const c = await cookies();
      c.set({
        name: COOKIE_NAME,
        value: language,
        domain: COOKIE_DOMAIN,
        path: "/",
        sameSite: "lax",
        secure: true,
        httpOnly: false,
        maxAge: ONE_YEAR_SECONDS,
      });
    }

    revalidatePath("/settings");
    return {
      success: true,
      message: language
        ? "Saved. Language change is live across all GoSec apps."
        : "Saved.",
    };
  } catch (err) {
    console.error("[settings] saveAccountSettings:", err);
    return { error: err instanceof Error ? err.message : "Failed to save settings." };
  }
}
