/**
 * Agent API v1 proxy.
 *
 * Exposes /api/agent/v1/* from tracker-web and forwards it to platform-service.
 * This gives coding agents a stable product-facing surface while the backend
 * owns auth, claim/close semantics, and persistence.
 */

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

const PLATFORM_API = process.env.PLATFORM_API_URL || 'http://localhost:4003';

async function proxy(req: NextRequest, { params }: { params: Promise<{ path: string[] }> }) {
  const { path } = await params;
  const targetPath = `/api/agent/v1/${path.join('/')}`;
  const url = new URL(targetPath, PLATFORM_API);

  req.nextUrl.searchParams.forEach((value, key) => {
    url.searchParams.set(key, value);
  });

  try {
    const headers: Record<string, string> = { 'Content-Type': 'application/json' };
    const auth = req.headers.get('authorization');
    const agentKey = req.headers.get('x-agent-key');
    const productId = req.headers.get('x-product-id');

    if (auth) headers.Authorization = auth;
    if (agentKey) headers['x-agent-key'] = agentKey;
    if (productId) headers['x-product-id'] = productId;

    const fetchOptions: RequestInit = {
      method: req.method,
      headers,
    };

    if (req.method !== 'GET' && req.method !== 'HEAD') {
      const body = await req.text();
      if (body) fetchOptions.body = body;
    }

    const res = await fetch(url.toString(), fetchOptions);
    const data = await res.text();

    return new NextResponse(data, {
      status: res.status,
      headers: { 'Content-Type': res.headers?.get('content-type') || 'application/json' },
    });
  } catch {
    return NextResponse.json({ error: 'Agent API unavailable' }, { status: 502 });
  }
}

export const GET = proxy;
export const POST = proxy;
export const PUT = proxy;
export const PATCH = proxy;
export const DELETE = proxy;
