import { fetchApi, API_BASE } from './client';
import type { Media } from './types';

export const mediaApi = {
  getAll: (relatedType?: string, relatedId?: string) => {
    const params = new URLSearchParams();
    if (relatedType) params.set('relatedType', relatedType);
    if (relatedId) params.set('relatedId', relatedId);
    const query = params.toString();
    return fetchApi<{ media: Media[] }>(`/api/media${query ? `?${query}` : ''}`);
  },

  upload: async (file: File, relatedId?: string, relatedType?: string) => {
    const formData = new FormData();
    formData.append('file', file);
    if (relatedId) formData.append('relatedId', relatedId);
    if (relatedType) formData.append('relatedType', relatedType);

    // Auth rides on the session cookie
    const res = await fetch(`${API_BASE}/api/media/upload`, {
      method: 'POST',
      credentials: API_BASE ? 'include' : 'same-origin',
      body: formData,
    });

    if (!res.ok) {
      const errorData = await res.json().catch(() => ({ error: 'Upload failed' }));
      throw new Error(errorData.error || 'Upload failed');
    }

    return res.json() as Promise<{ media: Media; url: string }>;
  },

  delete: (id: string) =>
    fetchApi<{ message: string }>(`/api/media/${id}`, { method: 'DELETE' }),
};
