import { NextRequest, NextResponse } from "next/server";

/*
| Runtime translation proxy (Google Cloud Translation v2). The API key
| stays server-side (GOOGLE_TRANSLATE_API_KEY); the browser only ever
| talks to this route. There is no message file anywhere — the client
| (app/lib/autoTranslate.ts) sends whatever English text is on screen and
| caches the answers.
|
| This endpoint spends a paid key, so it is deliberately boxed in:
| same-origin only, hindi only, capped batch/size, a small per-IP rate
| limit and a server-side cache so a repeated string is never billed twice.
*/

const GOOGLE_URL = "https://translation.googleapis.com/language/translate/v2";

const ALLOWED_TARGETS = new Set(["hi"]);
const MAX_TEXTS = 100;
const MAX_TEXT_LENGTH = 1500;
const MAX_TOTAL_CHARS = 12000;

const RATE_LIMIT = 90; // requests
const RATE_WINDOW_MS = 60_000;

const cache = new Map<string, string>();
const CACHE_LIMIT = 20000;

const hits = new Map<string, number[]>();

function rateLimited(ip: string): boolean {
  const now = Date.now();
  const recent = (hits.get(ip) ?? []).filter((t) => now - t < RATE_WINDOW_MS);
  recent.push(now);
  hits.set(ip, recent);

  if (hits.size > 5000) {
    for (const [key, times] of hits) {
      if (!times.some((t) => now - t < RATE_WINDOW_MS)) hits.delete(key);
    }
  }

  return recent.length > RATE_LIMIT;
}

// v2 can return HTML entities even for format=text on some inputs.
function decodeEntities(value: string): string {
  return value
    .replace(/&#39;|&apos;/g, "'")
    .replace(/&quot;/g, '"')
    .replace(/&lt;/g, "<")
    .replace(/&gt;/g, ">")
    .replace(/&amp;/g, "&");
}

function sameOrigin(request: NextRequest): boolean {
  const origin = request.headers.get("origin");
  if (!origin) return true; // non-browser callers carry no Origin; still rate limited

  try {
    return new URL(origin).host === request.headers.get("host");
  } catch {
    return false;
  }
}

export async function POST(request: NextRequest) {
  try {
    const apiKey = process.env.GOOGLE_TRANSLATE_API_KEY;

    if (!apiKey) {
      return NextResponse.json({ message: "Translation is not configured." }, { status: 503 });
    }

    if (!sameOrigin(request)) {
      return NextResponse.json({ message: "Forbidden." }, { status: 403 });
    }

    const ip = request.headers.get("x-forwarded-for")?.split(",")[0]?.trim() || "unknown";

    if (rateLimited(ip)) {
      return NextResponse.json({ message: "Too many requests." }, { status: 429 });
    }

    const body = await request.json();
    const target = String(body?.target ?? "");
    const texts: unknown = body?.texts;

    if (
      !ALLOWED_TARGETS.has(target) ||
      !Array.isArray(texts) ||
      texts.length === 0 ||
      texts.length > MAX_TEXTS ||
      texts.some((t) => typeof t !== "string" || !t.trim() || t.length > MAX_TEXT_LENGTH)
    ) {
      return NextResponse.json({ message: "Invalid request." }, { status: 400 });
    }

    const list = texts as string[];

    if (list.reduce((sum, t) => sum + t.length, 0) > MAX_TOTAL_CHARS) {
      return NextResponse.json({ message: "Request too large." }, { status: 413 });
    }

    const results: string[] = new Array(list.length);
    const missing: { index: number; text: string }[] = [];

    list.forEach((text, index) => {
      const hit = cache.get(`${target}:${text}`);
      if (hit !== undefined) results[index] = hit;
      else missing.push({ index, text });
    });

    if (missing.length > 0) {
      const unique = Array.from(new Set(missing.map((m) => m.text)));

      const response = await fetch(`${GOOGLE_URL}?key=${encodeURIComponent(apiKey)}`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ q: unique, source: "en", target, format: "text" }),
        cache: "no-store",
      });

      const data = await response.json();

      if (!response.ok) {
        console.error("Google Translate error:", response.status, data?.error?.message);
        return NextResponse.json(
          { message: "Translation service error." },
          { status: 502 },
        );
      }

      const translated: string[] = (data?.data?.translations ?? []).map(
        (t: { translatedText?: string }) => decodeEntities(t.translatedText ?? ""),
      );

      unique.forEach((text, i) => {
        if (translated[i]) {
          if (cache.size >= CACHE_LIMIT) cache.delete(cache.keys().next().value as string);
          cache.set(`${target}:${text}`, translated[i]);
        }
      });

      missing.forEach(({ index, text }) => {
        results[index] = cache.get(`${target}:${text}`) ?? text;
      });
    }

    return NextResponse.json({ translations: results });
  } catch (error) {
    console.error("Translate proxy error:", error);
    return NextResponse.json({ message: "Unable to translate." }, { status: 500 });
  }
}
