import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';
import { verifyJwtEdge } from '@/lib/auth-edge';

export async function middleware(req: NextRequest) {
  const { pathname } = req.nextUrl;

  // Bypass auth checks for login API and public/assets routes
  if (
    pathname.startsWith('/api/auth/login') ||
    pathname.startsWith('/api/auth/logout') ||
    pathname.startsWith('/_next') ||
    pathname.endsWith('.ico') ||
    pathname.endsWith('.svg') ||
    pathname.endsWith('.png') ||
    pathname.endsWith('.jpg')
  ) {
    return NextResponse.next();
  }

  // Get session cookie
  const allCookies = req.cookies.getAll();
  const sessionCookie = req.cookies.get('session')?.value;
  if (process.env.DEBUG === 'true') {
    console.log(`[Middleware] Path: ${pathname}, Cookies received:`, allCookies.map(c => c.name), "Session value exists:", !!sessionCookie);
  }
  const session = sessionCookie ? await verifyJwtEdge(sessionCookie) : null;

  // If on login page
  if (pathname === '/login') {
    if (session) {
      // User is already logged in, redirect to dashboard (home page)
      return NextResponse.redirect(new URL('/', req.url));
    }
    return NextResponse.next();
  }

  // If trying to access any other route and not logged in
  if (!session) {
    if (pathname.startsWith('/api/')) {
      return NextResponse.json(
        { error: 'No autorizado. La sesión ha expirado o no existe.' },
        { status: 401 }
      );
    }
    // Redirect to login page
    const loginUrl = new URL('/login', req.url);
    // Optional: save return URL
    loginUrl.searchParams.set('callbackUrl', pathname);
    return NextResponse.redirect(loginUrl);
  }

  // Role-based route authorization guards
  const role = session.role;

  // 1. /sales/import requires: admin, analyst, commercial_leader
  if (pathname.startsWith('/sales/import')) {
    const allowed = ['admin', 'analyst', 'commercial_leader'];
    if (!allowed.includes(role)) {
      return NextResponse.redirect(new URL('/unauthorized', req.url));
    }
  }

  // 2. /sales/simulation requires: admin, analyst
  if (pathname.startsWith('/sales/simulation')) {
    const allowed = ['admin', 'analyst'];
    if (!allowed.includes(role)) {
      return NextResponse.redirect(new URL('/unauthorized', req.url));
    }
  }

  // 3. /settlements/approvals requires: admin, analyst, director, commercial_leader
  if (pathname.startsWith('/settlements/approvals')) {
    const allowed = ['admin', 'analyst', 'director', 'commercial_leader'];
    if (!allowed.includes(role)) {
      return NextResponse.redirect(new URL('/unauthorized', req.url));
    }
  }

  // If accessing API routes, we can inject role headers or simply allow Next.js route guards to handle it
  const response = NextResponse.next();
  
  // Forward session details in request headers to simplify API role checking if needed
  response.headers.set('x-user-id', String(session.userId));
  response.headers.set('x-user-role', session.role);
  response.headers.set('x-user-hotel-id', String(session.hotelId));
  response.headers.set('x-user-region-id', String(session.regionId));

  return response;
}

export const config = {
  // Apply middleware to all routes except api routes that are not auth related (we will handle api auth directly in routes)
  matcher: ['/((?!api/n8n|api/sales/batch-save).*)']
};
