import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import createMiddleware from "next-intl/middleware";
import { locales, defaultLocale } from "./i18n/settings";

const intlMiddleware = createMiddleware({
  locales,
  defaultLocale,
  localePrefix: "always",
});

export default function middleware(request: NextRequest) {
  // Redirect docs.kubestellar.io before any other processing
  if (request.nextUrl.hostname === "docs.kubestellar.io") {
    const path = request.nextUrl.pathname;
    const target = path === "/" ? "/docs" : `/docs${path}`;
    return NextResponse.redirect(`https://kubestellar.io${target}`, 301);
  }

  // Redirect console-docs.kubestellar.io to console docs section
  if (request.nextUrl.hostname === "console-docs.kubestellar.io") {
    const path = request.nextUrl.pathname;
    const target = path === "/" ? "/docs/console/readme" : `/docs/console${path}`;
    return NextResponse.redirect(`https://kubestellar.io${target}`, 301);
  }

  // Redirect localized docs URLs to non-localized version
  // e.g., /es/docs/... -> /docs/...
  const docsPathMatch = request.nextUrl.pathname.match(/^\/([a-z]{2}(?:-[A-Z]{2})?|SC)\/docs\//);
  if (docsPathMatch) {
    const url = request.nextUrl.clone();
    // Remove the locale prefix from the pathname
    url.pathname = url.pathname.replace(/^\/[a-z]{2}(?:-[A-Z]{2})?\/docs\//, '/docs/').replace(/^\/SC\/docs\//, '/docs/');
    return NextResponse.redirect(url, 307);
  }

  // Explicitly handle root path to ensure consistent redirect to /en
  // This helps override any cached redirects in browsers like Safari
  if (request.nextUrl.pathname === "/") {
    const url = request.nextUrl.clone();
    url.pathname = `/${defaultLocale}`;
    return NextResponse.redirect(url, 307); // Use 307 to avoid aggressive caching
  }

  // Run the i18n middleware for everything else
  return intlMiddleware(request);
}

export const config = {
  matcher: [
    "/((?!docs|api|live|_next|_vercel|agenda|blog|code|community|drive|infomercial|join_us|joinus|ladder_stats|linkedin|quickstart|slack|survey|tv|youtube|.*\\..*).*)",
    "/",
  ],
};
