import { NextResponse } from "next/server";
import { registerOperatorWallet } from "@/lib/operator-wallets-db";

export const dynamic = "force-dynamic";
export const runtime = "nodejs";

const proxy = async (request: Request, context: { params: Promise<{ path: string[] }> }) => {
  const baseUrl = process.env.CONTROL_API_INTERNAL_URL;
  const internalToken = process.env.CONTROL_INTERNAL_TOKEN;
  if (!baseUrl || !internalToken) {
    return NextResponse.json({ error: "Operator control plane is not configured" }, { status: 503 });
  }

  const { path } = await context.params;
  const sourceUrl = new URL(request.url);
  const target = new URL(`/api/operator/${path.map(encodeURIComponent).join("/")}${sourceUrl.search}`, baseUrl);
  const headers = new Headers({
    "x-control-internal-token": internalToken,
    "accept": "application/json",
  });
  for (const name of ["content-type", "cookie", "origin", "x-csrf-token"]) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }

  try {
    const routePath = path.join("/");
    const timeout = routePath === "launch/predict" ? 240_000 : routePath === "logo" ? 120_000 : 15_000;
    const upstream = await fetch(target, {
      method: request.method,
      headers,
      body: request.method === "GET" || request.method === "HEAD" ? undefined : await request.arrayBuffer(),
      cache: "no-store",
      signal: AbortSignal.timeout(timeout),
    });
    const responseHeaders = new Headers({
      "content-type": upstream.headers.get("content-type") ?? "application/json; charset=utf-8",
      "cache-control": "no-store",
    });
    const setCookie = upstream.headers.get("set-cookie");
    if (setCookie) responseHeaders.set("set-cookie", setCookie);
    const responseBody = await upstream.arrayBuffer();
    if (request.method === "POST" && path.join("/") === "wallet" && upstream.status === 201) {
      const body = JSON.parse(new TextDecoder().decode(responseBody)) as { address?: string };
      if (body.address) registerOperatorWallet(body.address);
    }
    return new NextResponse(responseBody, { status: upstream.status, headers: responseHeaders });
  } catch {
    return NextResponse.json({ error: "Agent control service is unavailable" }, { status: 503 });
  }
};

export const GET = proxy;
export const POST = proxy;
