/**
 * Тонкий прокси к chat-svc. Вся логика uploads на бекенде.
 */
import { NextResponse } from 'next/server';

export async function POST(req: Request) {
  try {
    const formData = await req.formData();
    const chatUrl = process.env.CHAT_SVC_URL ?? 'http://localhost:3005';

    const newFormData = new FormData();
    const providerId = formData.get('embedding_model_provider_id');
    const modelKey = formData.get('embedding_model_key');
    if (providerId) newFormData.set('embedding_model_provider_id', String(providerId));
    if (modelKey) newFormData.set('embedding_model_key', String(modelKey));

    const files = formData.getAll('files');
    for (const f of files) {
      if (f instanceof File) newFormData.append('files', f);
    }

    const res = await fetch(`${chatUrl}/api/v1/uploads`, {
      method: 'POST',
      body: newFormData,
      signal: AbortSignal.timeout(300000),
    });

    const data = await res.json();
    return NextResponse.json(data, { status: res.status });
  } catch (err) {
    console.error('Upload proxy error:', err);
    return NextResponse.json({ message: 'An error has occurred.' }, { status: 500 });
  }
}
