import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { AUTH_COOKIE_NAME } from "@/lib/auth";

const protectedPrefixes = [
  "/dashboard",
  "/customers",
  "/locations",
  "/contacts",
  "/devices",
  "/equipment",
  "/validations",
  "/users",
  "/profile"
];

async function loadCurrentUser(request: NextRequest) {
  const response = await fetch(new URL("/api/me", request.url), {
    headers: { cookie: request.headers.get("cookie") ?? "" },
    cache: "no-store"
  });
  if (!response.ok) {
    return null;
  }
  return (await response.json()) as { must_change_password?: boolean };
}

export async function middleware(request: NextRequest) {
  const token = request.cookies.get(AUTH_COOKIE_NAME)?.value;
  const isProtected = protectedPrefixes.some(
    (prefix) => request.nextUrl.pathname === prefix || request.nextUrl.pathname.startsWith(`${prefix}/`)
  );

  if (!token) {
    if (isProtected) {
      return NextResponse.redirect(new URL("/login", request.url));
    }
    return NextResponse.next();
  }

  const currentUser = await loadCurrentUser(request);
  const requiresPasswordChange = Boolean(currentUser?.must_change_password);
  const isLogin = request.nextUrl.pathname === "/login";
  const isPasswordProfile = request.nextUrl.pathname === "/profile/security";

  if (isLogin) {
    const target = requiresPasswordChange ? "/profile/security" : "/dashboard";
    return NextResponse.redirect(new URL(target, request.url));
  }

  if (requiresPasswordChange && isProtected && !isPasswordProfile) {
    return NextResponse.redirect(new URL("/profile/security", request.url));
  }

  return NextResponse.next();
}

export const config = {
  matcher: ["/dashboard/:path*", "/customers/:path*", "/locations/:path*", "/contacts/:path*", "/devices/:path*", "/equipment/:path*", "/validations/:path*", "/users/:path*", "/profile/:path*", "/login"]
};
