import { NAV_ITEMS } from "@/config/navigation";
import { withAuth } from "next-auth/middleware";
import createMiddleware from "next-intl/middleware";
import type { NextRequest } from "next/server";
import type { NextMiddlewareResult } from "next/dist/server/web/types";
import { routing } from "./i18n/routing";

const publicPages = NAV_ITEMS.flatMap((item) => [
  ...(!item.protected ? [item.href] : []),
  ...(item.children
    ?.filter((child) => !child.protected)
    .map((child) => child.href) ?? []),
]);

const handleI18nRouting = createMiddleware(routing);

const authMiddleware = withAuth(
  // Note that this callback is only invoked if
  // the `authorized` callback has returned `true`
  // and not for pages listed in `pages`.
  function onSuccess(req) {
    return handleI18nRouting(req);
  },
  {
    callbacks: {
      authorized: ({ token }) => token != null,
    },
    pages: {
      signIn: "/home",
    },
  },
);

export default function proxy(req: NextRequest) {
  // CRITICAL: Skip API routes entirely - they should not go through i18n or auth middleware
  if (req.nextUrl.pathname.startsWith("/api/")) {
    return; // Return undefined to pass through without modification
  }

  const publicPathnameRegex = RegExp(
    `^(/(${routing.locales.join("|")}))?(${publicPages
      .flatMap((p) => (p === "/" ? ["", "/"] : p))
      .join("|")})/?$`,
    "i",
  );
  const isPublicPage = publicPathnameRegex.test(req.nextUrl.pathname);

  if (isPublicPage) {
    return handleI18nRouting(req);
  } else {
    return (
      authMiddleware as unknown as (req: NextRequest) => NextMiddlewareResult
    )(req);
  }
}

export const config = {
  matcher: "/((?!api|trpc|_next|_vercel|.*\\..*).*)",
  // matcher: ['/', '/(de|en|tr)/:path*'],
};
