import axios from 'axios'

const API_BASE_URL = import.meta.env.VITE_API_URL || 'http://localhost:3001/api'

export const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
  },
})

export interface ModelResponse {
  id: string
  name: string
  description?: string
  format: string
  file_size: number
  thumbnail_url?: string
  metadata?: any
  share_id: string
  url: string
  shareUrl: string
  created_at: string
  updated_at: string
}

export const modelsApi = {
  getAll: async (): Promise<ModelResponse[]> => {
    const { data } = await api.get('/models')
    return data
  },

  getById: async (id: string): Promise<ModelResponse> => {
    const { data } = await api.get(`/models/${id}`)
    return data
  },

  upload: async (file: File, metadata?: {
    name?: string
    description?: string
    metadata?: any
  }): Promise<ModelResponse> => {
    const formData = new FormData()
    formData.append('file', file)
    if (metadata?.name) formData.append('name', metadata.name)
    if (metadata?.description) formData.append('description', metadata.description)
    if (metadata?.metadata) formData.append('metadata', JSON.stringify(metadata.metadata))

    const { data } = await api.post('/models', formData, {
      headers: {
        'Content-Type': 'multipart/form-data',
      },
    })
    return data
  },

  delete: async (id: string): Promise<void> => {
    await api.delete(`/models/${id}`)
  },

  getFileUrl: (id: string): string => {
    return `${API_BASE_URL}/models/${id}/file`
  },
}

