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

function getApiBaseUrl(): string {
  return process.env.API_BASE_URL || 'http://localhost:8000';
}

export async function POST(request: NextRequest) {
  try {
    const formData = await request.formData();
    const apiBase = getApiBaseUrl();

    const headers: Record<string, string> = {};
    const authHeader = request.headers.get('authorization');
    if (authHeader) headers['authorization'] = authHeader;
    const tenantHeader = request.headers.get('x-tenant-id');
    if (tenantHeader) headers['x-tenant-id'] = tenantHeader;

    const response = await fetch(`${apiBase}/api/v1/versions/parse`, {
      method: 'POST',
      headers,
      body: formData,
    });

    const data = await response.text();
    return new NextResponse(data, {
      status: response.status,
      headers: { 'Content-Type': response.headers.get('Content-Type') || 'application/json' },
    });
  } catch (error) {
    console.error('[app-versions/parse] proxy error:', error);
    return NextResponse.json({ error: 'Parse proxy error', detail: String(error) }, { status: 502 });
  }
}

export const maxDuration = 120; // seconds
