import { SignJWT, jwtVerify } from "jose";

/** Domain-wide session cookie (the whole poc.digt.ch host sits behind it). */
export const SESSION_COOKIE = "poc_hub_session";

// The session proves identity only. Per-app access is resolved fresh from the
// directory at check time (so allowlist changes take effect without re-login);
// `admin` is cached here because the edge middleware can't read the directory file.
export type SessionUser = { email: string; name: string; admin: boolean };

function secret(): Uint8Array {
  return new TextEncoder().encode(process.env.AUTH_SECRET || "dev-insecure-hub-secret-change-me");
}

export async function createSessionToken(user: SessionUser): Promise<string> {
  return new SignJWT({ email: user.email, name: user.name, admin: user.admin })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("12h")
    .sign(secret());
}

export async function verifySessionToken(token?: string): Promise<SessionUser | null> {
  if (!token) return null;
  try {
    const { payload } = await jwtVerify(token, secret());
    return {
      email: String(payload.email),
      name: String(payload.name || payload.email),
      admin: payload.admin === true,
    };
  } catch {
    return null;
  }
}
