const USER = process.env.ADMIN_USER || 'admin';
const PASS = process.env.ADMIN_PASS || 'demo';
export function onRequest({ request }, next) {
  const url = new URL(request.url);
  if (url.pathname.startsWith('/admin')) {
    const hdr = request.headers.get('authorization') || '';
    if (hdr.startsWith('Basic ')) {
      let dec = ''; try { dec = atob(hdr.slice(6)); } catch {}
      const i = dec.indexOf(':');
      if (i > -1 && dec.slice(0, i) === USER && dec.slice(i + 1) === PASS) return next();
    }
    return new Response('Authentifizierung erforderlich', { status: 401, headers: { 'WWW-Authenticate': 'Basic realm="PMPNZNG Admin", charset="UTF-8"' } });
  }
  return next();
}
