import { SignJWT, jwtVerify } from "jose";
import { loadSystemConfig } from "../system-config";

export type SessionToken = {
  sub: string; // userId
  role: "ADMIN" | "USER";
  email: string;
  forcePasswordReset: boolean;
};

async function getSecret() {
  const cfg = await loadSystemConfig();
  const s = cfg.auth?.jwtSecret || process.env.JWT_SECRET;
  if (!s) return null;
  return new TextEncoder().encode(s);
}

export async function signSession(payload: SessionToken) {
  const secret = await getSecret();
  if (!secret) throw new Error("JWT secret not configured");
  const token = await new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("7d")
    .sign(secret);
  return token;
}

export async function verifySession(token: string) {
  const secret = await getSecret();
  if (!secret) return null;
  try {
    const { payload } = await jwtVerify(token, secret);
    return payload as any as SessionToken;
  } catch {
    return null;
  }
}
