import { apiClient } from '../../../core/api/client';
import type { CreateDocumentRequest, DocumentRecord, UpdateDocumentRequest } from '../types/documents.types';

export const documentsApi = {
  async list(params?: { vehicleId?: string; type?: string; expiresBefore?: string }) {
    const res = await apiClient.get<DocumentRecord[]>('/documents', { params });
    return res.data;
  },
  async get(id: string) {
    const res = await apiClient.get<DocumentRecord>(`/documents/${id}`);
    return res.data;
  },
  async create(payload: CreateDocumentRequest) {
    const res = await apiClient.post<DocumentRecord>('/documents', payload);
    return res.data;
  },
  async update(id: string, payload: UpdateDocumentRequest) {
    const res = await apiClient.put<DocumentRecord>(`/documents/${id}`, payload);
    return res.data;
  },
  async remove(id: string) {
    await apiClient.delete(`/documents/${id}`);
  },
  async upload(id: string, file: File) {
    const form = new FormData();
    form.append('file', file);
    const res = await apiClient.post<DocumentRecord>(`/documents/${id}/upload`, form, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    return res.data;
  },
  async uploadWithProgress(id: string, file: File, onProgress?: (percent: number) => void) {
    const form = new FormData();
    form.append('file', file);
    const res = await apiClient.post<DocumentRecord>(`/documents/${id}/upload`, form, {
      headers: { 'Content-Type': 'multipart/form-data' },
      onUploadProgress: (evt) => {
        if (evt.total) {
          const pct = Math.round((evt.loaded / evt.total) * 100);
          onProgress?.(pct);
        }
      },
    });
    return res.data;
  },
  async download(id: string) {
    // Return a blob for inline preview / download
    const res = await apiClient.get(`/documents/${id}/download`, { responseType: 'blob' });
    return res.data as Blob;
  }
};
