// /opt/newsoras/app/main/frontend/middleware.ts
import { NextRequest, NextResponse } from "next/server";
import {
  DEFAULT_LOCALE,
  isLocale,
  localeFromCountry,
  pickFromAcceptLanguage,
  LOCALES,
} from "@/lib/i18n";

const LOCALE_COOKIE = "site_locale";

function getCountry(req: NextRequest): string | null {
  const cf = req.headers.get("cf-ipcountry");
  if (cf) return cf;

  const vercel = req.headers.get("x-vercel-ip-country");
  if (vercel) return vercel;

  // @ts-ignore
  const geoCountry = req.geo?.country as string | undefined;
  return geoCountry ?? null;
}

function isPublicFile(pathname: string) {
  return /\.[a-zA-Z0-9]+$/.test(pathname);
}

function hasLocalePrefix(pathname: string): boolean {
  return LOCALES.some((l) => pathname === `/${l}` || pathname.startsWith(`/${l}/`));
}

function normalizePath(p: string) {
  // evita doble slash y asegura trailing slash
  const one = p.replace(/\/{2,}/g, "/");
  return one.endsWith("/") ? one : `${one}/`;
}

function getPublicOrigin(req: NextRequest): string {
  // Preferimos X-Forwarded-* (Nginx/Cloudflare)
  const proto =
    req.headers.get("x-forwarded-proto")?.split(",")[0]?.trim() ||
    "https";

  // OJO: en Cloudflare suele venir Host correcto. Nginx también debe setearlo.
  const host =
    req.headers.get("x-forwarded-host")?.split(",")[0]?.trim() ||
    req.headers.get("host")?.split(",")[0]?.trim() ||
    "www.newsoras.com";

  // Si por algún motivo te llega host con :3000, lo limpiamos:
  const cleanHost = host.replace(/:\d+$/, "");

  return `${proto}://${cleanHost}`;
}

function redirectAbsolute(req: NextRequest, pathname: string, search: string) {
  const origin = getPublicOrigin(req);
  const target = new URL(origin);
  target.pathname = pathname;
  target.search = search || "";
  return NextResponse.redirect(target, 307);
}

export function middleware(req: NextRequest) {
  const { pathname, search } = req.nextUrl;

  // No tocar assets / api
  if (
    pathname.startsWith("/_next") ||
    pathname.startsWith("/favicon.ico") ||
    pathname.startsWith("/api")
  ) {
    return NextResponse.next();
  }

  // No tocar archivos estáticos
  if (
    isPublicFile(pathname) ||
    pathname === "/robots.txt" ||
    pathname === "/sitemap.xml" ||
    pathname === "/manifest.webmanifest"
  ) {
    return NextResponse.next();
  }

  // Ya viene con locale
  if (hasLocalePrefix(pathname)) {
    return NextResponse.next();
  }

  // 1) Cookie
  const cookieLocale = req.cookies.get(LOCALE_COOKIE)?.value ?? null;
  if (cookieLocale && isLocale(cookieLocale)) {
    const targetPath = normalizePath(`/${cookieLocale}${pathname}`);
    return redirectAbsolute(req, targetPath, search);
  }

  // 2) Accept-Language
  const accept = req.headers.get("accept-language");
  const fromAccept = pickFromAcceptLanguage(accept);

  // 3) Country
  const country = getCountry(req);
  const fromCountry = localeFromCountry(country);

  const chosen = fromAccept ?? fromCountry ?? DEFAULT_LOCALE;
  const targetPath = normalizePath(`/${chosen}${pathname}`);

  return redirectAbsolute(req, targetPath, search);
}

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