/**
 * Extraction API proxy — forwards requests to extraction-service (port 4005).
 *
 * GET/POST /api/extraction/* → extraction-service /api/*
 */

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

const EXTRACTION_SERVICE_URL = process.env.EXTRACTION_SERVICE_URL || 'http://localhost:4005';

async function proxyToExtraction(
  req: NextRequest,
  { params }: { params: Promise<{ path: string[] }> }
) {
  try {
    const caller = await getCurrentUserFromRequest(req);
    if (!caller) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const { path } = await params;
    const targetPath = `/api/${path.join('/')}`;
    const url = new URL(req.url);
    const qs = url.search;

    const headers: Record<string, string> = {
      'Content-Type': 'application/json',
      'x-request-id': req.headers.get('x-request-id') || crypto.randomUUID(),
      'x-user-id': caller.id,
    };

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

    if (req.method === 'POST' || req.method === 'PUT') {
      fetchOptions.body = await req.text();
    }

    const res = await fetch(`${EXTRACTION_SERVICE_URL}${targetPath}${qs}`, fetchOptions);

    const data = await res.json().catch(() => null);

    return NextResponse.json(data ?? { error: res.statusText }, {
      status: res.status,
    });
  } catch (error) {
    logError('Extraction proxy error', error);
    return NextResponse.json({ error: 'Extraction service unavailable' }, { status: 502 });
  }
}

export async function GET(req: NextRequest, context: { params: Promise<{ path: string[] }> }) {
  return proxyToExtraction(req, context);
}

export async function POST(req: NextRequest, context: { params: Promise<{ path: string[] }> }) {
  return proxyToExtraction(req, context);
}

export async function PUT(req: NextRequest, context: { params: Promise<{ path: string[] }> }) {
  return proxyToExtraction(req, context);
}

export async function DELETE(req: NextRequest, context: { params: Promise<{ path: string[] }> }) {
  return proxyToExtraction(req, context);
}
