// Simple token auth using Web Crypto API (works in both browser and server)
// For production, use JWT or NextAuth.js sessions

const SECRET = 'ummi-monitoring-secret-key-2024';

function toBase64Url(data: Uint8Array): string {
  let binary = '';
  for (let i = 0; i < data.length; i++) binary += String.fromCharCode(data[i]);
  return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
}

function fromBase64Url(str: string): Uint8Array {
  const base64 = str.replace(/-/g, '+').replace(/_/g, '/');
  const binary = atob(base64);
  const bytes = new Uint8Array(binary.length);
  for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);
  return bytes;
}

async function sha256(message: string): Promise<string> {
  const encoder = new TextEncoder();
  const data = encoder.encode(message);
  const hashBuffer = await crypto.subtle.digest('SHA-256', data);
  return toBase64Url(new Uint8Array(hashBuffer));
}

function encodeObj(obj: unknown): string {
  const encoder = new TextEncoder();
  return toBase64Url(encoder.encode(JSON.stringify(obj)));
}

function decodeObj(str: string): unknown {
  const bytes = fromBase64Url(str);
  const decoder = new TextDecoder();
  return JSON.parse(decoder.decode(bytes));
}

export async function createToken(payload: Record<string, unknown>): Promise<string> {
  const header = encodeObj({ alg: 'HS256', typ: 'JWT' });
  const body = encodeObj({ ...payload, iat: Date.now() });
  const signature = await sha256(`${header}.${body}.${SECRET}`);
  return `${header}.${body}.${signature}`;
}

export async function verifyToken(token: string): Promise<Record<string, unknown> | null> {
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;

    const [header, body, signature] = parts;
    const expectedSignature = await sha256(`${header}.${body}.${SECRET}`);

    if (signature !== expectedSignature) return null;

    return decodeObj(body) as Record<string, unknown>;
  } catch {
    return null;
  }
}