import { randomBytes } from 'node:crypto';

export const ADMIN_PASSWORD = '27182818';
export const ADMIN_COOKIE = 'admin_session';
export const ADMIN_TTL_SECONDS = 5 * 60;

// A fresh token is minted at server startup, so any cookies that survived a
// restart are invalidated. There's no shared cookie value to forge.
export const ADMIN_TOKEN = randomBytes(32).toString('hex');

export function adminCookieOptions() {
  return {
    path: '/admin',
    httpOnly: true,
    sameSite: 'lax',
    maxAge: ADMIN_TTL_SECONDS
  };
}

export function isAdminAuthed(event) {
  return event.cookies.get(ADMIN_COOKIE) === ADMIN_TOKEN;
}

export function refreshAdminCookie(event) {
  event.cookies.set(ADMIN_COOKIE, ADMIN_TOKEN, adminCookieOptions());
}

export function isAdminPath(pathname) {
  return pathname === '/admin' || pathname.startsWith('/admin/');
}

export function isLoginPath(pathname) {
  return pathname === '/admin/login' || pathname.startsWith('/admin/login/');
}
