import "server-only";
import { SignJWT, jwtVerify } from "jose";

const ISSUER = "orthoglobe";
const AUDIENCE = "orthoglobe-admin-approval";

function key() {
  const secret = process.env.APPROVAL_TOKEN_SECRET;
  if (!secret) throw new Error("APPROVAL_TOKEN_SECRET not set");
  return new TextEncoder().encode(secret);
}

export async function signApprovalToken(applicationId: string): Promise<string> {
  return new SignJWT({ applicationId })
    .setProtectedHeader({ alg: "HS256" })
    .setIssuer(ISSUER)
    .setAudience(AUDIENCE)
    .setIssuedAt()
    .setExpirationTime("7d")
    .sign(key());
}

export async function verifyApprovalToken(token: string): Promise<{ applicationId: string }> {
  const { payload } = await jwtVerify(token, key(), { issuer: ISSUER, audience: AUDIENCE });
  if (typeof payload.applicationId !== "string") throw new Error("invalid token payload");
  return { applicationId: payload.applicationId };
}
