/**
 * JWT utilities — consolidated from Python + TS implementations.
 * Uses jose library for standards-compliant JWT handling.
 */

import { SignJWT, jwtVerify } from 'jose';

function getSecret(): Uint8Array {
  const secret = process.env.JWT_SECRET;
  if (!secret) throw new Error('JWT_SECRET must be set');
  return new TextEncoder().encode(secret);
}

export async function createAccessToken(payload: {
  sub: string;
  email: string;
  role: string;
  productId: string;
  plan?: 'free' | 'pro' | 'enterprise';
  displayName?: string;
}): Promise<string> {
  return new SignJWT({ ...payload, type: 'access' })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('1h')
    .setIssuer('bytelyst-platform')
    .sign(getSecret());
}

export async function createRefreshToken(payload: {
  sub: string;
  productId: string;
}): Promise<string> {
  return new SignJWT({ sub: payload.sub, productId: payload.productId, type: 'refresh' })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('7d')
    .setIssuer('bytelyst-platform')
    .sign(getSecret());
}

export async function verifyToken(token: string): Promise<{
  sub: string;
  email?: string;
  role?: string;
  productId?: string;
  plan?: 'free' | 'pro' | 'enterprise';
  displayName?: string;
  type?: string;
}> {
  const { payload } = await jwtVerify(token, getSecret(), {
    issuer: 'bytelyst-platform',
  });
  return payload as {
    sub: string;
    email?: string;
    role?: string;
    productId?: string;
    plan?: 'free' | 'pro' | 'enterprise';
    displayName?: string;
    type?: string;
  };
}
