import { NextRequest, NextResponse } from 'next/server';
import { jwtVerify } from 'jose';

const JWT_SECRET = new TextEncoder().encode(
  process.env.JWT_SECRET || 'usfloral-secret-key-2024'
);

const protectedRoutes = [
  '/dashboard',
  '/products',
  '/customers',
  '/farms',
  '/orders',
  '/ordenes',
  '/cold-room',
  '/tracking',
  '/pedidos',
  '/parametros',
  '/usuarios',
  '/reports',
  '/registro'
];
const authRoutes = ['/login'];

export async function middleware(request: NextRequest) {
  const token = request.cookies.get('auth-token')?.value;
  const { pathname } = request.nextUrl;

  const isProtected = protectedRoutes.some(route => pathname === route || pathname.startsWith(route + '/'));
  const isAuthRoute = authRoutes.some(route => pathname.startsWith(route));

  let isValidToken = false;
  let userPayload: any = null;

  if (token) {
    try {
      const verified = await jwtVerify(token, JWT_SECRET);
      isValidToken = true;
      userPayload = verified.payload;
    } catch {
      isValidToken = false;
    }
  }

  // Not logged in and trying to access protected route
  if (isProtected && !isValidToken) {
    return NextResponse.redirect(new URL('/login', request.url));
  }

  // Logged in and on auth route (/login)
  if (isAuthRoute && isValidToken) {
    const role = userPayload?.role;
    if (role === 'FARM') {
      return NextResponse.redirect(new URL('/pedidos', request.url));
    } else if (role === 'COLD_ROOM') {
      return NextResponse.redirect(new URL('/cold-room', request.url));
    }
    return NextResponse.redirect(new URL('/dashboard', request.url));
  }

  // Role-based restrictions for protected routes
  if (isValidToken && userPayload?.role) {
    const role = userPayload.role;

    // FARM role: only allowed on /pedidos
    if (role === 'FARM') {
      const isAllowed = pathname.startsWith('/pedidos');
      if (!isAllowed && isProtected) {
        return NextResponse.redirect(new URL('/pedidos', request.url));
      }
    }

    // COLD_ROOM role: only allowed on /cold-room and /tracking
    if (role === 'COLD_ROOM') {
      const isAllowed = pathname.startsWith('/cold-room') || pathname.startsWith('/tracking');
      if (!isAllowed && isProtected) {
        return NextResponse.redirect(new URL('/cold-room', request.url));
      }
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: ['/((?!api|_next/static|_next/image|favicon.ico|.*\\.png|.*\\.jpg|.*\\.svg).*)'],
};
