import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { jwtVerify } from "jose";

if (!process.env.JWT_SECRET) {
  console.error("coloca el JWT_SECRET en el .env")
}

const secret = new TextEncoder().encode(process.env.JWT_SECRET);

export async function proxy(request: NextRequest) {
  const token = request.cookies.get("token")?.value;
  const pathname = request.nextUrl.pathname;

  if (!token && pathname !== "/") {
    const response = NextResponse.redirect(new URL("/", request.url));

    response.cookies.delete("user");
    response.cookies.delete("token");
    return response;
  }

  if (pathname === "/" && token) {
    return NextResponse.redirect(new URL("/Impresiones", request.url));
  }

  if (token) {
    try {
      const { payload } = await jwtVerify(token, secret);

      const role = payload.role as number;

      const onlyImpresiones = ["/Impresiones"];

      const limitedRoutes = [
        "/Inscripcion",
        "/Alta",
        "/AgregarTiempo",
        "/Impresiones",
        "/AsignacionMesas",
        "/AsignacionEquipo",
        "/Monitor",
        "/ActivosMantenimiento",
        "/Periodo",
      ];

      if (role === 5 && !onlyImpresiones.includes(pathname)) {
        return NextResponse.redirect(new URL("/Impresiones", request.url));
      }

      if ((role === 2 || role === 3) && !limitedRoutes.includes(pathname)) {
        return NextResponse.redirect(new URL("/Impresiones", request.url));
      }

    } catch (error) {
      const response = NextResponse.redirect(new URL("/", request.url));
      response.cookies.delete("token");
      response.cookies.delete("user");
      return response;
    }
  }

  return NextResponse.next();
}

export const config = {
  matcher: [
    "/",
    "/Reportes",
    "/Periodo",
    "/Monitor",
    "/QuitarSancion",
    "/Programas",
    "/Mensajes",
    "/Inscritos",
    "/Inscripcion",
    "/InformacionEquipo",
    "/Impresiones",
    "/CambiarPass",
    "/BitacoraSanciones",
    "/AsignacionMesas",
    "/AsignacionEquipo",
    "/Alta",
    "/AgregarTiempo",
    "/ActivosMantenimiento",
  ],
};