import { defineMiddleware } from 'astro/middleware';
import { getSessionUser } from './lib/auth.js';

const PUBLIC = ['/login', '/invite'];

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

  const isPublic = PUBLIC.some(p => pathname === p || pathname.startsWith(p + '/'));
  if (isPublic) return next();

  const user = getSessionUser(ctx.cookies);
  if (!user) return ctx.redirect('/login');

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