import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import createMiddleware from "next-intl/middleware";
import { routing } from "./i18n/routing";
import { getCountryByDomain, supportedLocales } from "./lib/countries";
import {
  getAuthUser,
  isProtectedClientRoute,
  isProtectedFreelancerRoute,
  getRedirectUrl,
} from "./lib/auth-middleware";

// Initialize next-intl middleware
const intlMiddleware = createMiddleware(routing);

export async function middleware(request: NextRequest) {
  const { pathname, hostname } = request.nextUrl;

  console.log("🚀 Middleware triggered for:", pathname);

  // Skip middleware for static files and API routes
  if (
    pathname.startsWith("/_next") ||
    pathname.startsWith("/api") ||
    pathname.startsWith("/assets") ||
    pathname.includes(".")
  ) {
    console.log("⏭️ Skipping middleware for:", pathname);
    return NextResponse.next();
  }

  // 🗺️ Locale handling (Next-Intl middleware)
  const intlResponse = intlMiddleware(request);
  if (intlResponse) {
    // intlMiddleware may redirect (for example, to add a default locale)
    if (intlResponse.redirected) return intlResponse;
  }

  // 🌍 Country detection
  let country = getCountryByDomain(hostname);

  if (
    !country &&
    (hostname === "localhost" || hostname.includes("localhost"))
  ) {
    country = {
      id: "localhost",
      name: "Development",
      code: "US",
      domain: "localhost:3000",
      languages: ["en", "fr", "de", "it", "pt", "es"],
      defaultLanguage: "en",
      currency: "USD",
      currencySymbol: "$",
      packagePrice: 9.9,
      paymentGateways: ["stripe"],
    };
  } else if (!country) {
    country = getCountryByDomain("smile24.ch"); // fallback
  }

  if (!country) {
    return intlResponse || NextResponse.next();
  }

  // 🌐 Locale validation based on country
  const pathnameHasLocale = supportedLocales.some(
    (locale) => pathname.startsWith(`/${locale}/`) || pathname === `/${locale}`
  );

  if (pathnameHasLocale) {
    const locale = pathname.split("/")[1];
    if (!country.languages.includes(locale)) {
      const newUrl = new URL(request.url);
      newUrl.pathname = pathname.replace(
        `/${locale}`,
        `/${country.defaultLanguage}`
      );
      return NextResponse.redirect(newUrl);
    }

    // 🔒 Protected route check (delegated to layout)
    if (
      isProtectedClientRoute(pathname) ||
      isProtectedFreelancerRoute(pathname)
    ) {
      console.log(
        "🔒 Protected route detected (skipping middleware check):",
        pathname
      );
    }

    // Add country headers
    const response = intlResponse || NextResponse.next();
    response.headers.set("x-country-code", country.code);
    response.headers.set("x-country-domain", country.domain);
    return response;
  }

  // No locale in pathname → redirect to default locale
  const newUrl = new URL(request.url);
  newUrl.pathname = `/${country.defaultLanguage}${pathname}`;
  return NextResponse.redirect(newUrl);
}

// ✅ Define routes to match all supported locales from `routing.ts`
export const config = {
  matcher: [
    "/",
    "/(en|fr|de|it|pt|es)/:path*",
    "/((?!api|_next/static|_next/image|favicon.ico|assets).*)",
  ],
};
