import { supabase } from './supabase.js';

// Admins aus der .env (ADMIN_EMAILS=a@x,b@y). Admins sehen/bearbeiten alles.
const ADMINS = (process.env.ADMIN_EMAILS || '')
  .split(',').map((s) => s.trim().toLowerCase()).filter(Boolean);

// Verifiziert den Supabase-Access-Token und legt user/email/isAdmin im Kontext ab.
export async function requireAuth(c, next) {
  const header = c.req.header('Authorization') || '';
  const token = header.startsWith('Bearer ') ? header.slice(7) : null;
  if (!token) return c.json({ error: 'Nicht eingeloggt' }, 401);

  const { data, error } = await supabase.auth.getUser(token);
  if (error || !data?.user) return c.json({ error: 'Ungültiges Token' }, 401);

  const email = (data.user.email || '').toLowerCase();
  c.set('user', data.user);
  c.set('email', email);
  c.set('isAdmin', ADMINS.includes(email));
  await next();
}

// Nur Admins (nach requireAuth einsetzen).
export async function requireAdmin(c, next) {
  if (!c.get('isAdmin')) return c.json({ error: 'Nur für Admins' }, 403);
  await next();
}
