import { defineMiddleware } from 'astro:middleware';
import { getTokenFromRequest, verifyToken } from './lib/auth';

const isStaging = process.env.NODE_ENV === 'staging' || process.env.PORT === '3002';

export const onRequest = defineMiddleware(async ({ request, url }, next) => {
  // Protect admin API routes (except login)
  if (url.pathname.startsWith('/api/admin/') && !url.pathname.includes('/auth/login')) {
    const token = getTokenFromRequest(request);
    if (!token || !verifyToken(token)) {
      return new Response(JSON.stringify({ error: 'Unauthorized' }), {
        status: 401,
        headers: { 'Content-Type': 'application/json' },
      });
    }
  }

  const response = await next();

  // Add X-Robots-Tag for staging
  if (isStaging) {
    response.headers.set('X-Robots-Tag', 'noindex, nofollow');
  }

  return response;
});
