// Auto-generated by AutoCRUD Web Generator
import { client } from '../../lib/client';
import type { BlobUploadSession, BlobFinalizeResult } from '../../types/api';
import type { AxiosProgressEvent } from 'axios';

const BLOBS = '/v1/autocrud/blobs';

export const blobApi = {
  /**
   * Simple single-file upload via multipart/form-data.
   * For small files that don't need chunked upload.
   */
  upload: (
    file: File,
    options?: { onUploadProgress?: (e: AxiosProgressEvent) => void; signal?: AbortSignal },
  ) => {
    const form = new FormData();
    form.append('file', file);
    return client.post<{ file_id: string; size: number; content_type: string }>(
      `${BLOBS}/upload`,
      form,
      {
        headers: { 'Content-Type': 'multipart/form-data' },
        onUploadProgress: options?.onUploadProgress,
        signal: options?.signal,
      },
    );
  },

  /**
   * Create an upload session for chunked / parallel uploads.
   */
  createUploadSession: (
    params: { content_type: string; size: number; total_parts?: number },
    signal?: AbortSignal,
  ) => client.post<BlobUploadSession>(`${BLOBS}/upload-sessions`, params, { signal }),

  /**
   * Get the current state of an upload session.
   */
  getUploadSession: (uploadId: string) =>
    client.get<BlobUploadSession>(`${BLOBS}/upload-sessions/${uploadId}`),

  /**
   * Upload a chunk of bytes to an upload session.
   * Use `partNumber` for parallel uploads so the server can reassemble in order.
   */
  uploadChunk: (
    uploadId: string,
    chunk: Blob,
    options?: {
      fileName?: string;
      partNumber?: number;
      onUploadProgress?: (e: AxiosProgressEvent) => void;
      signal?: AbortSignal;
    },
  ) => {
    const form = new FormData();
    form.append('file', chunk, options?.fileName);
    return client.put<BlobUploadSession>(`${BLOBS}/upload-sessions/${uploadId}/content`, form, {
      params: options?.partNumber != null ? { part_number: options.partNumber } : undefined,
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: options?.onUploadProgress,
      signal: options?.signal,
    });
  },

  /**
   * Finalize an upload session — commits buffered bytes to the blob store.
   * Returns final Binary metadata (file_id, size, content_type).
   */
  finalizeUploadSession: (uploadId: string, signal?: AbortSignal) =>
    client.post<BlobFinalizeResult>(`${BLOBS}/upload-sessions/${uploadId}/finalize`, null, {
      signal,
    }),

  /**
   * Abort an upload session — discards all uploaded data.
   */
  abortUploadSession: (uploadId: string) =>
    client.post<void>(`${BLOBS}/upload-sessions/${uploadId}/abort`),
};
