import { NextRequest, NextResponse } from "next/server";
import createMiddleware from "next-intl/middleware";

import { routing } from "./i18n/routing";
import { ROUTES } from "./shared/constants/client-routes";

const publicRoutes = [
  ROUTES.authCallback(),
  ROUTES.paymentSuccess(),
  ROUTES.paymentFailed(),
];

function isPublicRoute(pathname: string): boolean {
  const pathWithoutLocale = pathname.replace(/^\/[a-z]{2}\//, "/");
  return publicRoutes.some(route => pathWithoutLocale.startsWith(route));
}

function createAuthMiddleware() {
  return async function authMiddleware(request: NextRequest) {
    const pathname = request.nextUrl.pathname;

    if (isPublicRoute(pathname)) {
      return NextResponse.next();
    }

    const token = request.cookies.get("accessToken")?.value;

    if (!token) {
      return NextResponse.redirect(
        process.env.NEXT_PUBLIC_AUTH_REDIRECT_URL || ""
      );
    }

    return NextResponse.next();
  };
}

const intlMiddleware = createMiddleware(routing);

export default async function middleware(request: NextRequest) {
  const authResponse = await createAuthMiddleware()(request);
  if (authResponse.status !== 200 && process.env.NODE_ENV === "production") {
    return authResponse;
  }

  return intlMiddleware(request);
}

export const config = {
  // Match all pathnames except for
  // - … if they start with `/api`, `/trpc`, `/_next` or `/_vercel`
  // - … the ones containing a dot (e.g. `favicon.ico`)
  matcher: "/((?!api|trpc|_next|_vercel|.*\\..*).*)",
};
