import { NextRequest, NextResponse } from "next/server"; import { jwtVerify } from "jose"; const SECRET = new TextEncoder().encode(process.env.NEXTAUTH_SECRET || "dev-secret"); async function verifyCookie(req: NextRequest, cookieName: string) { const token = req.cookies.get(cookieName)?.value; if (!token) return false; try { await jwtVerify(token, SECRET); return true; } 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"); 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"); if (!ok) return NextResponse.redirect(new URL("/admin", req.url)); } if (pathname.startsWith("/jefe/dashboard")) { const ok = await verifyCookie(req, "jefe_session"); if (!ok) return NextResponse.redirect(new URL("/jefe", req.url)); } return NextResponse.next(); } export const config = { matcher: ["/cliente/:path*", "/admin/:path*", "/jefe/:path*"], };