export interface UserSession {
  userId: number;
  username: string;
  email: string;
  role: string;
  hotelId: number;
  regionId: number;
}

if (!process.env.NEXTAUTH_SECRET) {
  throw new Error('FATAL: NEXTAUTH_SECRET environment variable is missing.');
}
const JWT_SECRET = process.env.NEXTAUTH_SECRET;

function base64urlDecode(str: string): string {
  let base64 = str.replace(/-/g, '+').replace(/_/g, '/');
  while (base64.length % 4) {
    base64 += '=';
  }
  return atob(base64);
}

/**
 * Verifies a JWT natively in the Edge Runtime using Web Crypto API.
 */
export async function verifyJwtEdge(token: string): Promise<UserSession | null> {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;
    
    const [headerB64, payloadB64, signatureB64] = parts;
    
    const encoder = new TextEncoder();
    const keyData = encoder.encode(JWT_SECRET);
    
    const key = await crypto.subtle.importKey(
      'raw',
      keyData,
      { name: 'HMAC', hash: { name: 'SHA-256' } },
      false,
      ['verify']
    );
    
    // Decode base64url signature to binary array
    let base64Sig = signatureB64.replace(/-/g, '+').replace(/_/g, '/');
    while (base64Sig.length % 4) {
      base64Sig += '=';
    }
    
    const signatureBin = atob(base64Sig);
    const signatureBuf = new Uint8Array(signatureBin.length);
    for (let i = 0; i < signatureBin.length; i++) {
      signatureBuf[i] = signatureBin.charCodeAt(i);
    }
    
    const dataBuf = encoder.encode(`${headerB64}.${payloadB64}`);
    const isValid = await crypto.subtle.verify(
      'HMAC',
      key,
      signatureBuf,
      dataBuf
    );
    
    if (!isValid) return null;
    
    const payload = JSON.parse(base64urlDecode(payloadB64));
    
    // Check expiration
    if (payload.exp && Date.now() / 1000 > payload.exp) {
      return null;
    }
    
    return payload as UserSession;
  } catch (err) {
    console.error('Edge JWT verification error:', err);
    return null;
  }
}
