import { defineMiddleware } from 'astro:middleware';
import { authService } from './services/auth';

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

  // Check if the route is under /admin/
  if (url.pathname.startsWith('/admin/')) {
    // Get token from cookie
    const token = cookies.get('payload-token')?.value;

    if (!token) {
      // Redirect to CMS login subdomain
      return redirect('https://cms.enchun.tw/admin/login');
    }

    // Validate token
    authService.setToken(token);
    const user = await authService.getCurrentUser();

    if (!user) {
      // Token invalid, redirect to login
      cookies.delete('payload-token');
      return redirect('https://cms.enchun.tw/admin/login');
    }

    // User authenticated, proceed
    // Could add role checks here if needed
  }

  return next();
});