/**
 * JWT RS256 token signing for StyloBridge licenses.
 *
 * Produces tokens with identical claims to scripts/gen_license.py,
 * validated by src/license.py on the client side.
 */

import { SignJWT, importPKCS8 } from "jose";

export interface TokenParams {
  sub: string;
  tier: "standard" | "enterprise";
  seats: number;
  days: number;
}

export interface SignedToken {
  token: string;
  expires: string; // ISO 8601
}

export async function signLicenseToken(
  params: TokenParams,
  privateKeyPem: string
): Promise<SignedToken> {
  const privateKey = await importPKCS8(privateKeyPem, "RS256");

  const now = Math.floor(Date.now() / 1000);
  const exp = now + params.days * 86400;

  const token = await new SignJWT({
    sub: params.sub,
    tier: params.tier,
    seats: params.seats,
  })
    .setProtectedHeader({ alg: "RS256" })
    .setIssuer("stylobridge")
    .setAudience("stylobridge")
    .setIssuedAt(now)
    .setExpirationTime(exp)
    .sign(privateKey);

  return {
    token,
    expires: new Date(exp * 1000).toISOString(),
  };
}
