import crypto from 'crypto';

const SECRET = process.env.AUTH_SECRET || 'voting-system-secret-key-2024';
const COOKIE_NAME = 'voting_session';

export interface AuthUser {
  employeeId: string;
  name: string;
  branchId: string;
  branchName: string;
  isAdmin: boolean;
  dbId: string;
}

function sign(value: string): string {
  const sig = crypto.createHmac('sha256', SECRET).update(value).digest('base64url');
  return `${value}.${sig}`;
}

function verify(token: string): string | null {
  const dotIndex = token.lastIndexOf('.');
  if (dotIndex === -1) return null;
  const value = token.substring(0, dotIndex);
  const sig = token.substring(dotIndex + 1);
  const expected = crypto.createHmac('sha256', SECRET).update(value).digest('base64url');
  if (sig !== expected) return null;
  return value;
}

export function createSessionToken(user: AuthUser): string {
  const payload = JSON.stringify({
    eid: user.employeeId,
    name: user.name,
    bid: user.branchId,
    bn: user.branchName,
    adm: user.isAdmin,
    did: user.dbId,
  });
  return sign(payload);
}

export function verifySessionToken(token: string): AuthUser | null {
  const payload = verify(token);
  if (!payload) return null;
  try {
    const data = JSON.parse(payload);
    return {
      employeeId: data.eid,
      name: data.name,
      branchId: data.bid,
      branchName: data.bn,
      isAdmin: data.adm,
      dbId: data.did,
    };
  } catch {
    return null;
  }
}

export function getAuthUser(request: Request): AuthUser | null {
  const cookieHeader = request.headers.get('cookie') || '';
  const cookies = Object.fromEntries(
    cookieHeader.split(';').map(c => {
      const [key, ...v] = c.trim().split('=');
      return [key, v.join('=')];
    })
  );
  const token = cookies[COOKIE_NAME];
  if (!token) return null;
  return verifySessionToken(decodeURIComponent(token));
}

export function setSessionCookie(token: string): string {
  return `${COOKIE_NAME}=${encodeURIComponent(token)}; HttpOnly; Path=/; SameSite=Strict; Max-Age=${60 * 60 * 24}`;
}

export function clearSessionCookie(): string {
  return `${COOKIE_NAME}=; HttpOnly; Path=/; SameSite=Strict; Max-Age=0`;
}

export function hashPin(pin: string): string {
  return crypto.createHash('sha256').update(pin).digest('hex');
}

export function generateId(): string {
  return crypto.randomUUID();
}
