import { UpstreamHttpError } from '../../../../lib/errors/upstream_http_error';
import { ragFetch } from '../../../../lib/helpers/rag_config';
import type { RagUploadResult } from './types';

export interface UploadFileArgs {
  file: Blob;
  filename: string;
  contentType: string;
  fileId: string;
  metadata?: Record<string, unknown>;
  timeoutMs?: number;
  sync?: boolean;
  /** Required: RAG resolves the org's provider catalog from this slug. */
  orgSlug: string;
}

interface RagApiUploadResponse {
  file_id?: string;
  id?: string;
  success?: boolean;
  chunks_created?: number;
}

/**
 * Upload a file to the RAG service via multipart/form-data.
 */
const SYNC_TIMEOUT_MS = 120_000;
const DEFAULT_TIMEOUT_MS = 30_000;

export async function uploadFile({
  file,
  filename,
  contentType,
  fileId,
  metadata,
  timeoutMs,
  sync = false,
  orgSlug,
}: UploadFileArgs): Promise<RagUploadResult> {
  const effectiveTimeout =
    timeoutMs ?? (sync ? SYNC_TIMEOUT_MS : DEFAULT_TIMEOUT_MS);
  const startTime = Date.now();

  const formData = new FormData();
  formData.append('file', file, filename);
  formData.append('file_id', fileId);
  formData.append(
    'metadata',
    JSON.stringify({ ...metadata, content_type: contentType }),
  );

  const path = sync
    ? '/api/v1/documents/upload?sync=true'
    : '/api/v1/documents/upload';

  const response = await ragFetch(path, {
    method: 'POST',
    body: formData,
    timeoutMs: effectiveTimeout,
    orgSlug,
  });

  if (!response.ok) {
    const errorText = await response.text();
    throw UpstreamHttpError.fromResponse('rag', response, errorText, path);
  }

  // oxlint-disable-next-line typescript/no-unsafe-type-assertion -- typed response
  const result = (await response.json()) as RagApiUploadResponse;
  const ragDocumentId = result.file_id || result.id;

  return {
    success: result.success ?? true,
    fileId,
    ragDocumentId,
    chunksCreated: result.chunks_created || 0,
    processingTimeMs: Date.now() - startTime,
    timestamp: Date.now(),
  };
}
