import { NextRequest, NextResponse } from 'next/server';
import { getCurrentUserFromRequest } from '@/lib/auth-server';
import { logError } from '@/lib/logger';

const PLATFORM_URL = process.env.PLATFORM_SERVICE_URL || 'http://localhost:4003';
const COWORK_SERVICE_URL = process.env.COWORK_SERVICE_URL || 'http://localhost:4009';

function buildHeaders(req: NextRequest, callerId: string): Record<string, string> {
  return {
    'Content-Type': 'application/json',
    'x-request-id': req.headers.get('x-request-id') || crypto.randomUUID(),
    'x-user-id': callerId,
    'x-product-id': req.headers.get('x-product-id') || process.env.PRODUCT_ID || 'lysnrai',
  };
}

export async function GET(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const url = new URL(req.url);
    const section = url.searchParams.get('section') ?? 'sessions';
    const productOverride = url.searchParams.get('productId')?.trim() || null;
    const qs = new URLSearchParams(url.searchParams);
    qs.delete('section');
    qs.delete('productId');
    const suffix = qs.toString() ? `?${qs.toString()}` : '';
    const targetProductId =
      productOverride || req.headers.get('x-product-id') || process.env.PRODUCT_ID || 'lysnrai';
    const isCowork = targetProductId === 'clawcowork';

    let targetBaseUrl = PLATFORM_URL;
    let targetPath = `/api/agent-runtime/sessions${suffix}`;
    if (section === 'runs') {
      targetPath = `/api/agent-runtime/runs${suffix}`;
    } else if (isCowork && section === 'checkpoints') {
      targetBaseUrl = COWORK_SERVICE_URL;
      targetPath = `/api/agent-runtime/checkpoints${suffix}`;
    } else if (isCowork && section === 'checkpoint-detail') {
      const checkpointId = url.searchParams.get('checkpointId')?.trim();
      if (!checkpointId) {
        return NextResponse.json({ error: 'checkpointId is required' }, { status: 400 });
      }
      targetBaseUrl = COWORK_SERVICE_URL;
      targetPath = `/api/agent-runtime/checkpoints/${encodeURIComponent(checkpointId)}`;
    }

    const res = await fetch(`${targetBaseUrl}${targetPath}`, {
      method: 'GET',
      headers: {
        ...buildHeaders(req, caller.id),
        'x-product-id': targetProductId,
      },
    });

    const data = await res.json().catch(() => null);
    return NextResponse.json(data ?? { error: res.statusText }, { status: res.status });
  } catch (error) {
    logError('Agent runtime proxy GET error', error);
    return NextResponse.json({ error: 'Service unavailable' }, { status: 502 });
  }
}

export async function POST(req: NextRequest) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });

    const res = await fetch(`${PLATFORM_URL}/api/agent-runtime/dispatch/validate`, {
      method: 'POST',
      headers: buildHeaders(req, caller.id),
      body: await req.text(),
    });

    const data = await res.json().catch(() => null);
    return NextResponse.json(data ?? { error: res.statusText }, { status: res.status });
  } catch (error) {
    logError('Agent runtime proxy POST error', error);
    return NextResponse.json({ error: 'Service unavailable' }, { status: 502 });
  }
}
