import api from './client'

export interface AssetLibraryCatalog {
  materials: string[]
  node_groups: string[]
}

export interface AssetLibrary {
  id: string
  name: string
  description: string | null
  original_filename: string | null
  catalog: AssetLibraryCatalog
  is_active: boolean
  created_at: string
  updated_at: string
}

export async function listAssetLibraries(): Promise<AssetLibrary[]> {
  const { data } = await api.get<AssetLibrary[]>('/asset-libraries')
  return data
}

export async function getAssetLibrary(id: string): Promise<AssetLibrary> {
  const { data } = await api.get<AssetLibrary>(`/asset-libraries/${id}`)
  return data
}

export async function createAssetLibrary(params: {
  name: string
  description?: string
  blend_file: File
}): Promise<AssetLibrary> {
  const form = new FormData()
  form.append('name', params.name)
  if (params.description) form.append('description', params.description)
  form.append('blend_file', params.blend_file)
  const { data } = await api.post<AssetLibrary>('/asset-libraries', form, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return data
}

export async function uploadAssetLibraryBlend(id: string, file: File): Promise<AssetLibrary> {
  const form = new FormData()
  form.append('blend_file', file)
  const { data } = await api.post<AssetLibrary>(`/asset-libraries/${id}/upload-blend`, form, {
    headers: { 'Content-Type': 'multipart/form-data' },
  })
  return data
}

export async function refreshAssetLibraryCatalog(id: string): Promise<AssetLibrary> {
  const { data } = await api.post<AssetLibrary>(`/asset-libraries/${id}/refresh-catalog`)
  return data
}

export async function deleteAssetLibrary(id: string): Promise<void> {
  await api.delete(`/asset-libraries/${id}`)
}
