import { NextResponse, type NextRequest } from "next/server";
import { API_ORIGIN } from "@/lib/apiOrigin";
import { clientIpFrom } from "@/lib/clientIp";
import type { PublicRegion } from "@/app/(site)/_lib/content";
import { DIVISION_BASE, getDivision } from "@/app/(site)/_lib/divisions";
import { GLOBAL, resolveLanding } from "@/app/(site)/_lib/landing";
import { FALLBACK_REGIONS } from "@/app/(site)/_lib/regions";

/** Set once a visitor has been on a landing page; while present, / is never redirected. */
const REGION_COOKIE = "ug_region";
const ONE_YEAR = 60 * 60 * 24 * 365;

/**
 * First-visit geo redirect on /. Off unless GEO_REDIRECT=1: the API must trust the
 * X-Forwarded-For this app sends (it ignores it as of 2026-11-18). Until it does,
 * it locates the server, and every visitor would be sent to the server's region.
 */
const GEO_REDIRECT = process.env.GEO_REDIRECT === "1";

/** Search engines, link previews and audit tools always get the page they asked for. */
const BOT_UA = /bot|crawl|spider|slurp|bingpreview|facebookexternalhit|embedly|quora link preview|whatsapp|telegram|skype|lighthouse|headless|pagespeed|preview/i;

export async function proxy(request: NextRequest) {
  const ip = clientIpFrom(request.headers.get("x-forwarded-for"));
  const { pathname, search } = request.nextUrl;

  /*
   * /api/v1/* → the CMS API (rewrite in next.config.ts). Without this the API only
   * sees this server's address. Next fills x-forwarded-for with the connecting
   * address when the request has none; clientIpFrom keeps the one trusted entry.
   */
  if (pathname.startsWith("/api/")) {
    const headers = new Headers(request.headers);
    if (ip) headers.set("x-forwarded-for", ip);
    else headers.delete("x-forwarded-for");
    return NextResponse.next({ request: { headers } });
  }

  // Service pages (/services/<slug>): an unknown slug is a real 404 (see "Landing URLs" below for why here).
  if (pathname.startsWith(DIVISION_BASE + "/")) {
    const slug = pathname.slice(DIVISION_BASE.length + 1).replace(/\/$/, "");
    if (!slug.includes("/") && !(await serviceExists(slug))) return NextResponse.rewrite(new URL("/_not-found", request.url), { status: 404 });
    return NextResponse.next();
  }

  // Product and article pages (/products/<slug>, /articles/<slug>): 404 for unknown ones, a permanent redirect for an old slug.
  for (const base of [PRODUCT_BASE, ARTICLE_BASE]) {
    if (!pathname.startsWith(base + "/")) continue;
    const slug = pathname.slice(base.length + 1).replace(/\/$/, "");
    if (slug.includes("/")) return NextResponse.next();
    const found = await slugLookup(base, slug);
    if (found === "not-found") return NextResponse.rewrite(new URL("/_not-found", request.url), { status: 404 });
    if (found && found !== slug) return NextResponse.redirect(new URL(`${base}/${found}${search}`, request.url), 308);
    return NextResponse.next();
  }

  // Landing pages (/, /we, /we/fr, /fr).
  const landing = await checkLandingUrl(pathname);
  if (landing === "not-found") return NextResponse.rewrite(new URL("/_not-found", request.url), { status: 404 });
  if (landing) return NextResponse.redirect(new URL(landing + search, request.url), 308);

  const hasCookie = request.cookies.has(REGION_COOKIE);
  const ua = request.headers.get("user-agent") ?? "";
  const isBot = !ua || BOT_UA.test(ua);

  if (pathname === "/" && GEO_REDIRECT && !hasCookie && !isBot && request.method === "GET") {
    const detected = await detectRegionPath(ip);
    // Lookup failed or timed out: show / without remembering anything, so the next visit tries again.
    if (detected === null) return NextResponse.next();
    if (detected !== "/") {
      const res = NextResponse.redirect(new URL(detected + search, request.url), 302);
      res.headers.set("Cache-Control", "private, no-store");
      res.cookies.set(REGION_COOKIE, detected.slice(1), { path: "/", maxAge: ONE_YEAR, sameSite: "lax" });
      return res;
    }
  }

  const res = NextResponse.next();
  // Remember that this visitor has seen a landing page, so a later visit to / isn't redirected.
  if (GEO_REDIRECT && !hasCookie && !isBot) {
    res.cookies.set(REGION_COOKIE, pathname.split("/")[1] || "global", { path: "/", maxAge: ONE_YEAR, sameSite: "lax" });
  }
  return res;
}

/* ------------------------------------------------------------------ */
/* Landing URLs                                                        */
/* ------------------------------------------------------------------ */

/*
 * The pages resolve URLs too, but with Cache Components an unknown param renders at
 * request time, after the response has started streaming, so a redirect or 404 there
 * is sent as 200. Doing it here gives search engines real 308 / 404 status codes.
 */
let regionCache: { at: number; regions: PublicRegion[] } | null = null;

async function regions(): Promise<PublicRegion[]> {
  if (regionCache && Date.now() - regionCache.at < 60_000) return regionCache.regions;
  try {
    const res = await fetch(`${API_ORIGIN}/api/v1/public/regions`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(1500) });
    const list = res.ok ? ((await res.json()) as { data: PublicRegion[] }).data : null;
    if (list?.length) regionCache = { at: Date.now(), regions: list };
  } catch {
    // keep the previous list
  }
  return regionCache?.regions ?? FALLBACK_REGIONS;
}

/**
 * A canonical URL to redirect to, "not-found", or null (render as usual).
 * An unknown single segment (/xyz) is left to the app: it may be a static page.
 * Under a known region, an unknown language is a real 404.
 */
async function checkLandingUrl(pathname: string): Promise<string | "not-found" | null> {
  const [first, second] = pathname.split("/").filter(Boolean);
  if (!first) return null;
  const list = await regions();
  const resolved = resolveLanding(list, first, second);
  if (resolved && "redirect" in resolved) return resolved.redirect;
  if (!resolved && second && (first === GLOBAL || list.some((r) => r.code === first))) return "not-found";
  return null;
}

/* ------------------------------------------------------------------ */
/* Services, products and articles                                     */
/* ------------------------------------------------------------------ */

const PRODUCT_BASE = "/products";
const ARTICLE_BASE = "/articles";
const LOOKUP_TTL = 60_000;

let serviceCache: { at: number; slugs: Set<string> } | null = null;

/** Slugs of the published services (GET /public/services), refreshed every minute; null when the API can't be reached. */
async function publishedServiceSlugs(): Promise<Set<string> | null> {
  if (serviceCache && Date.now() - serviceCache.at < LOOKUP_TTL) return serviceCache.slugs;
  try {
    const res = await fetch(`${API_ORIGIN}/api/v1/public/services?lang=en`, { headers: { Accept: "application/json" }, signal: AbortSignal.timeout(1500) });
    if (!res.ok) return serviceCache?.slugs ?? null;
    const { data } = (await res.json()) as { data: { divisions: { services: { slug: string }[] }[] } };
    serviceCache = { at: Date.now(), slugs: new Set(data.divisions.flatMap((d) => d.services.map((s) => s.slug))) };
    return serviceCache.slugs;
  } catch {
    return serviceCache?.slugs ?? null;
  }
}

/**
 * Same rule as the page (app/(site)/services/[slug]/page.tsx): once a service is
 * published the CMS decides; before that, the built-in services exist. Unknown when the
 * API is down: let the page decide.
 */
async function serviceExists(slug: string): Promise<boolean> {
  const published = await publishedServiceSlugs();
  if (!published) return true;
  return published.size > 0 ? published.has(slug) : !!getDivision(slug);
}

const slugCache = new Map<string, { at: number; result: string | "not-found" | null }>();

/**
 * The current slug of a product or article ("not-found" when it isn't on the website),
 * following an old slug's 301; null when the API can't answer (the page decides).
 * Cached a minute. `base` is the website path, the same as the API's (/products, /articles).
 */
async function slugLookup(base: string, slug: string): Promise<string | "not-found" | null> {
  if (!/^[a-z0-9]+(?:-[a-z0-9]+)*$/.test(slug)) return "not-found";
  const key = `${base}/${slug}`;
  const hit = slugCache.get(key);
  if (hit && Date.now() - hit.at < LOOKUP_TTL) return hit.result;
  let result: string | "not-found" | null = null;
  try {
    const res = await fetch(`${API_ORIGIN}/api/v1/public${base}/${slug}?lang=en`, { headers: { Accept: "application/json" }, redirect: "manual", signal: AbortSignal.timeout(1500) });
    if (res.status === 404) result = "not-found";
    else if (res.status >= 300 && res.status < 400) {
      const to = new RegExp(`/public${base}/([a-z0-9-]+)`).exec(res.headers.get("location") ?? "")?.[1];
      result = to ?? null;
    } else if (res.ok) result = slug;
  } catch {
    result = null;
  }
  if (result !== null) {
    if (slugCache.size > 500) slugCache.clear();
    slugCache.set(key, { at: Date.now(), result });
  }
  return result;
}

/** The detected region's path ("/we"), or null when the IP's country is unknown or the lookup fails. */
async function detectRegionPath(ip: string | undefined): Promise<string | null> {
  if (!ip) return null;
  try {
    const res = await fetch(`${API_ORIGIN}/api/v1/public/locale`, {
      headers: { Accept: "application/json", "X-Forwarded-For": ip },
      // Caps the extra wait on a first visit. Server-to-API is normally well under this;
      // through a VPN it can take 2-3 s.
      signal: AbortSignal.timeout(3000),
    });
    if (!res.ok) return null;
    const { data } = (await res.json()) as {
      data: { region: { path: string }; detection: { country: string | null; method: string } };
    };
    return data.detection.method === "ip" && data.detection.country ? data.region.path : null;
  } catch {
    return null;
  }
}

export const config = {
  matcher: ["/api/v1/:path*", "/services/:slug", "/products/:slug", "/articles/:slug", "/", "/:region([a-z]{2,6})", "/:region([a-z]{2,6})/:lang([a-zA-Z-]{2,10})"],
};
