// ---------------------------------------------------------------------------
// Uploads API client  (client-side)
// ---------------------------------------------------------------------------

import { apiFetch } from './client';

// ---------------------------------------------------------------------------
// Response shapes
// TODO: import from @/lib/types once the shared types package is finalised
// ---------------------------------------------------------------------------

export interface UploadResult {
  url: string;
  file_name: string;
  file_size: number;
  mime_type: string;
}

export interface MessageResponse {
  message: string;
}

// ---------------------------------------------------------------------------
// API functions
// ---------------------------------------------------------------------------

/**
 * Upload an image file.
 * @param file  The image file to upload
 * @param category  Storage category (default: "images")
 */
export function uploadImage(
  file: File,
  category?: string,
): Promise<UploadResult> {
  const formData = new FormData();
  formData.append('file', file);

  const qs = category ? `?category=${encodeURIComponent(category)}` : '';
  return apiFetch<UploadResult>(`/uploads/image/${qs}`, {
    method: 'POST',
    body: formData,
  });
}

/**
 * Upload a document file.
 * @param file  The document file to upload
 */
export function uploadDocument(file: File): Promise<UploadResult> {
  const formData = new FormData();
  formData.append('file', file);

  return apiFetch<UploadResult>('/uploads/document/', {
    method: 'POST',
    body: formData,
  });
}

/**
 * Upload a task completion photo.
 * @param file  The photo file to upload
 */
export function uploadCompletion(file: File): Promise<UploadResult> {
  const formData = new FormData();
  formData.append('file', file);

  return apiFetch<UploadResult>('/uploads/completion/', {
    method: 'POST',
    body: formData,
  });
}

/**
 * Delete an uploaded file by URL.
 * @param url  The URL of the file to delete
 */
export function deleteFile(url: string): Promise<MessageResponse> {
  return apiFetch<MessageResponse>('/uploads/', {
    method: 'DELETE',
    body: JSON.stringify({ url }),
  });
}
