const COOKIE_NAME = 'xhiva_session';
const SESSION_DURATION = 7 * 24 * 60 * 60 * 1000; // 7 days

function getPassword(): string {
  return process.env.ADMIN_PASSWORD || '';
}

async function sign(timestamp: number): Promise<string> {
  const password = getPassword();
  const encoder = new TextEncoder();
  const key = await crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'HMAC', hash: 'SHA-256' },
    false,
    ['sign']
  );
  const signature = await crypto.subtle.sign('HMAC', key, encoder.encode(String(timestamp)));
  return Array.from(new Uint8Array(signature))
    .map(b => b.toString(16).padStart(2, '0'))
    .join('');
}

export async function createSessionToken(): Promise<string> {
  const timestamp = Date.now();
  const sig = await sign(timestamp);
  return `${timestamp}.${sig}`;
}

export async function verifySessionToken(token: string): Promise<boolean> {
  const password = getPassword();
  if (!password) return false;

  const parts = token.split('.');
  if (parts.length !== 2) return false;

  const timestamp = parseInt(parts[0], 10);
  if (isNaN(timestamp)) return false;

  // Check expiry
  if (Date.now() - timestamp > SESSION_DURATION) return false;

  // Check signature
  const expected = await sign(timestamp);
  return parts[1] === expected;
}

export function validatePassword(input: string): boolean {
  const password = getPassword();
  if (!password) return false;
  return input === password;
}

export function getSessionCookie(token: string): string {
  const maxAge = SESSION_DURATION / 1000;
  return `${COOKIE_NAME}=${token}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}`;
}

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

export function getTokenFromCookies(cookieHeader: string | null): string | null {
  if (!cookieHeader) return null;
  const match = cookieHeader.match(new RegExp(`(?:^|;\\s*)${COOKIE_NAME}=([^;]*)`));
  return match ? match[1] : null;
}
