import { SignJWT, jwtVerify } from "jose";

// Partagé entre le middleware (edge) et le serveur : pas de dépendance Node ici.

export const COOKIE_SESSION = "erp_session";
const DUREE_SESSION_S = 60 * 60 * 12; // une journée de travail

export type DonneesSession = { uid: string; role: string; nom: string };

function cle() {
  const secret = process.env.SESSION_SECRET;
  if (!secret || secret.length < 32) {
    throw new Error("SESSION_SECRET manquant ou trop court (32 caractères minimum).");
  }
  return new TextEncoder().encode(secret);
}

export async function signerSession(donnees: DonneesSession) {
  return new SignJWT(donnees)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime(`${DUREE_SESSION_S}s`)
    .sign(cle());
}

export async function lireSession(jeton: string | undefined): Promise<DonneesSession | null> {
  if (!jeton) return null;
  try {
    const { payload } = await jwtVerify(jeton, cle(), { algorithms: ["HS256"] });
    return { uid: String(payload.uid), role: String(payload.role), nom: String(payload.nom) };
  } catch {
    return null;
  }
}

export const optionsCookie = {
  httpOnly: true,
  sameSite: "lax" as const,
  secure: process.env.NODE_ENV === "production",
  path: "/",
  maxAge: DUREE_SESSION_S,
};
