import { NextResponse } from "next/server";
import type { NextRequest } from "next/server";
import { LOCALES, DEFAULT_LOCALE, isLocale } from "@/app/i18n/locales";

// Gives astrotalk.com-style URLs (/hi/..., /kn/...) without moving any
// existing route under an app/[locale] folder: a locale-prefixed path
// is rewritten to the real (unprefixed) route, and the resolved locale
// is stamped on a cookie so server/client code can read it via
// LanguageProvider — see app/context/LanguageContext.tsx.
export function proxy(request: NextRequest) {
  const { pathname } = request.nextUrl;

  const segments = pathname.split("/");
  const maybeLocale = segments[1];

  if (isLocale(maybeLocale)) {
    const rest = "/" + segments.slice(2).join("/");
    const url = request.nextUrl.clone();
    url.pathname = rest;

    const response = NextResponse.rewrite(url);
    response.cookies.set("NEXT_LOCALE", maybeLocale, { path: "/" });
    return response;
  }

  const response = NextResponse.next();
  response.cookies.set("NEXT_LOCALE", DEFAULT_LOCALE, { path: "/" });
  return response;
}

export const config = {
  matcher: ["/((?!api|_next/static|_next/image|.*\\..*).*)"],
};
