// JWT helpers using `jose` instead of `jsonwebtoken` because jose runs
// in both Node.js and Edge runtimes. Next.js middleware runs on Edge,
// and we want to verify tokens there without pulling in Node crypto.

import { SignJWT, jwtVerify, JWTPayload } from 'jose';

const SECRET = process.env.JWT_SECRET;
const EXPIRES_IN = process.env.JWT_EXPIRES_IN || '7d';

if (!SECRET) {
  throw new Error('JWT_SECRET is not set in environment');
}

const encodedSecret = new TextEncoder().encode(SECRET);

export interface AppJwtPayload extends JWTPayload {
  userId: number;
  role: 'ADMIN' | 'EMPLOYEE';
  email: string;
  name: string;
}

export async function signToken(payload: Omit<AppJwtPayload, 'iat' | 'exp'>): Promise<string> {
  return await new SignJWT(payload)
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime(EXPIRES_IN)
    .sign(encodedSecret);
}

export async function verifyToken(token: string): Promise<AppJwtPayload | null> {
  try {
    const { payload } = await jwtVerify(token, encodedSecret);
    return payload as AppJwtPayload;
  } catch {
    return null;
  }
}
