import { jwtVerify, SignJWT } from "jose"

let encoded: Uint8Array

export function getJWTSecret(): Uint8Array {
  if (!encoded) {
    const raw = process.env.JWT_SECRET
    if (!raw) {
      throw new Error(
        "JWT_SECRET environment variable is required. " +
          "Generate one: openssl rand -hex 32",
      )
    }
    encoded = new TextEncoder().encode(raw)
  }
  return encoded
}

export async function verifyToken(token: string) {
  try {
    const { payload } = await jwtVerify(token, getJWTSecret())
    return payload as { userId: string; role: string }
  } catch {
    return null
  }
}

export async function signToken(payload: { userId: string; role: string }) {
  return new SignJWT(payload)
    .setProtectedHeader({ alg: "HS256" })
    .setExpirationTime("24h")
    .setIssuedAt()
    .sign(getJWTSecret())
}
