import { defineMiddleware } from 'astro:middleware';
import { getDb } from './lib/db';
import { getSessionUser, SESSION_COOKIE, canAccessAdminPath, landingFor } from './lib/auth';

export const onRequest = defineMiddleware((context, next) => {
  const { pathname } = context.url;
  const isProtected =
    (pathname.startsWith('/admin') && pathname !== '/admin/login') ||
    pathname.startsWith('/api/admin');
  if (!isProtected) return next();

  const token = context.cookies.get(SESSION_COOKIE)?.value;
  const user = token ? getSessionUser(getDb(), token) : null;
  if (!user) {
    if (pathname.startsWith('/api/')) {
      return new Response(JSON.stringify({ error: 'Non autorizzato' }), {
        status: 401, headers: { 'Content-Type': 'application/json' },
      });
    }
    return context.redirect('/admin/login');
  }

  if (!canAccessAdminPath(user.role, pathname)) {
    if (pathname.startsWith('/api/')) {
      return new Response(JSON.stringify({ error: 'Permessi insufficienti' }), {
        status: 403, headers: { 'Content-Type': 'application/json' },
      });
    }
    return context.redirect(landingFor(user.role));
  }

  context.locals.user = user;
  return next();
});
