import { NextRequest, NextResponse } from "next/server"; import { jwtVerify } from "jose"; const SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || "dev-secret"); // Las tres sesiones se firman con el mismo secreto, así que además de la firma hay // que mirar el rol: si no, un token de jefe en la cookie del cliente pasa. async function verifyCookie(req: NextRequest, cookieName: string, rol: "admin" | "cliente" | "jefe") { const token = req.cookies.get(cookieName)?.value; if (!token) return false; try { const { payload } = await jwtVerify(token, SECRET); return (payload as { role?: string }).role === rol; } catch { return false; } } export async function middleware(req: NextRequest) { const { pathname } = req.nextUrl; if (pathname.startsWith("/cliente/dashboard") || pathname.startsWith("/cliente/historial") || pathname.startsWith("/cliente/perfil") || pathname.startsWith("/cliente/turnos")) { const ok = await verifyCookie(req, "cliente_session", "cliente"); if (!ok) return NextResponse.redirect(new URL("/cliente", req.url)); } if (pathname.startsWith("/admin/dashboard") || pathname.startsWith("/admin/turnos") || pathname.startsWith("/admin/historial") || pathname.startsWith("/admin/servicios") || pathname.startsWith("/admin/jefes") || pathname.startsWith("/admin/clientes")) { const ok = await verifyCookie(req, "admin_session", "admin"); if (!ok) return NextResponse.redirect(new URL("/admin", req.url)); } if (pathname.startsWith("/jefe/dashboard")) { const ok = await verifyCookie(req, "jefe_session", "jefe"); if (!ok) return NextResponse.redirect(new URL("/jefe", req.url)); } return NextResponse.next(); } export const config = { matcher: ["/cliente/:path*", "/admin/:path*", "/jefe/:path*"], };