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();

    // Forward auth headers but let fetch set Content-Type with correct boundary for FormData
    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/upload`, {
      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/upload] proxy error:', error);
    return NextResponse.json({ error: 'Upload proxy error', detail: String(error) }, { status: 502 });
  }
}

// Disable body size limit for large APK/IPA uploads (up to 500 MB)
export const maxDuration = 300; // seconds
