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

const PUBLIC_ROUTES = ["/", "/tarifs", "/contact", "/connexion", "/inscription", "/mot-de-passe-oublie", "/reinitialiser-mot-de-passe"];
const AUTH_ROUTES = ["/connexion", "/inscription"];
const ADMIN_ROUTES = ["/admin"];

export default auth((req: NextRequest & { auth: any }) => {
  const { pathname } = req.nextUrl;
  const session = req.auth;
  const isAuthenticated = !!session?.user;

  // Redirection si déjà connecté sur pages auth
  if (isAuthenticated && AUTH_ROUTES.some((r) => pathname.startsWith(r))) {
    return NextResponse.redirect(new URL("/tableau-de-bord", req.url));
  }

  // Protection routes admin
  if (ADMIN_ROUTES.some((r) => pathname.startsWith(r))) {
    if (!isAuthenticated) {
      return NextResponse.redirect(new URL("/connexion", req.url));
    }
    if (!(session.user as any).isSuperAdmin) {
      return NextResponse.redirect(new URL("/tableau-de-bord", req.url));
    }
  }

  // Protection routes dashboard
  if (
    !PUBLIC_ROUTES.some((r) => pathname === r) &&
    !PUBLIC_ROUTES.some((r) => r !== "/" && pathname.startsWith(r)) &&
    !pathname.startsWith("/api") &&
    !pathname.startsWith("/_next") &&
    !pathname.startsWith("/images") &&
    !isAuthenticated
  ) {
    const callbackUrl = encodeURIComponent(pathname);
    return NextResponse.redirect(new URL(`/connexion?callbackUrl=${callbackUrl}`, req.url));
  }

  return NextResponse.next();
});

export const config = {
  matcher: ["/((?!_next/static|_next/image|favicon.ico|.*\\.(?:svg|png|jpg|jpeg|gif|webp)$).*)"],
};
