import { NextRequest, NextResponse } from "next/server";

const protectedPaths = ["/", "/cliente", "/vistorias", "/admin", "/excecoes", "/lixeira"];
const decode = (value: string) => atob(value.replace(/-/g, "+").replace(/_/g, "/"));

async function signatureIsValid(payload: string, signature: string, secret: string) {
  const key = await crypto.subtle.importKey("raw", new TextEncoder().encode(secret), { name: "HMAC", hash: "SHA-256" }, false, ["verify"]);
  const raw = Uint8Array.from(atob(signature.replace(/-/g, "+").replace(/_/g, "/")), value => value.charCodeAt(0));
  return crypto.subtle.verify("HMAC", key, raw, new TextEncoder().encode(payload));
}

export async function middleware(request: NextRequest) {
  const path = request.nextUrl.pathname;
  if (path === "/login" || path.startsWith("/vistoria/") || path.startsWith("/api/vistoria/") || path.startsWith("/api/auth/")) return NextResponse.next();
  if (!protectedPaths.some(item => item === "/" ? path === "/" : path.startsWith(item))) return NextResponse.next();
  const value = request.cookies.get("autovistoria_session")?.value;
  if (!value) return NextResponse.redirect(new URL("/login", request.url));
  const [payload, signature] = value.split(".");
  if (!payload || !signature) return NextResponse.redirect(new URL("/login", request.url));
  const secret = process.env.APP_SECRET || "troque-esta-chave-em-producao";
  try {
    if (!await signatureIsValid(payload, signature, secret)) throw new Error();
    const session = JSON.parse(decode(payload));
    if (session.exp < Date.now()) throw new Error();
    const isClient = String(session.role).startsWith("client_");
    let supportValid = false;
    const supportValue = request.cookies.get("autovistoria_support_tenant")?.value;
    if (supportValue && session.role === "capital_admin") {
      const [supportPayload, supportSignature] = supportValue.split(".");
      if (supportPayload && supportSignature && await signatureIsValid(supportPayload, supportSignature, secret)) {
        const support = JSON.parse(decode(supportPayload));
        supportValid = support.mode === "capital_support" && support.exp > Date.now() && support.operatorId === session.userId && Boolean(support.tenantId);
      }
    }
    if (path.startsWith("/cliente") && !isClient && !supportValid) return NextResponse.redirect(new URL("/", request.url));
    if (isClient && (path === "/" || path.startsWith("/vistorias") || path.startsWith("/admin") || path.startsWith("/excecoes") || path.startsWith("/lixeira") || path.startsWith("/perfil"))) return NextResponse.redirect(new URL("/cliente", request.url));
    return NextResponse.next();
  } catch { return NextResponse.redirect(new URL("/login", request.url)); }
}

export const config = { matcher: ["/", "/cliente/:path*", "/vistorias/:path*", "/admin/:path*", "/excecoes/:path*", "/lixeira/:path*"] };
