import { defineMiddleware } from 'astro:middleware';
import { ADMIN_COOKIE, verifySession } from './lib/auth';

export const onRequest = defineMiddleware(async (context, next) => {
  const { pathname } = context.url;

  const isAdminPage = pathname.startsWith('/admin') && pathname !== '/admin/login';
  const isAdminApi =
    pathname.startsWith('/api/content') ||
    pathname.startsWith('/api/upload') ||
    pathname === '/api/auth/logout';

  if (isAdminPage || isAdminApi) {
    const token = context.cookies.get(ADMIN_COOKIE)?.value;
    const ok = await verifySession(token);
    if (!ok) {
      if (isAdminApi) {
        return new Response(JSON.stringify({ error: 'unauthorized' }), {
          status: 401,
          headers: { 'Content-Type': 'application/json' },
        });
      }
      return context.redirect('/admin/login');
    }
  }

  return next();
});
