import type { AppEnv } from '@/types/hono';
import type { MiddlewareHandler } from 'hono';

function getSuperAdminEmails(): Set<string> {
  const raw = Bun.env.SUPER_ADMIN_EMAILS ?? '';
  const emails = raw
    .split(',')
    .map((value) => value.trim().toLowerCase())
    .filter(Boolean);
  return new Set(emails);
}

export const requireSuperAdmin: MiddlewareHandler<AppEnv> = async (c, next) => {
  const user = c.get('user');
  const role = (user as any).role || 'member';
  const email = user.email.toLowerCase();

  if (role === 'super_admin') {
    await next();
    return;
  }

  if (email && getSuperAdminEmails().has(email)) {
    await next();
    return;
  }

  return c.json({ message: 'Este recurso requiere permisos de super admin.' }, 403);
};
