import api from './client'

export type MediaAssetType =
  | 'thumbnail'
  | 'still'
  | 'turntable'
  | 'stl_low'
  | 'stl_high'
  | 'gltf_geometry'
  | 'gltf_production'
  | 'blend_production'

export interface MediaAsset {
  id: string
  tenant_id: string | null
  product_id: string | null
  cad_file_id: string | null
  order_line_id: string | null
  workflow_run_id: string | null
  asset_type: MediaAssetType
  storage_key: string
  file_size_bytes: number | null
  mime_type: string | null
  width: number | null
  height: number | null
  duration_s: number | null
  render_config: Record<string, unknown> | null
  is_archived: boolean
  created_at: string
  download_url: string | null
  thumbnail_url: string | null
}

export interface MediaFilter {
  product_id?: string
  order_line_id?: string
  cad_file_id?: string
  asset_types?: MediaAssetType[]
  skip?: number
  limit?: number
  sort_by?: string
  sort_dir?: 'asc' | 'desc'
}

export const getMediaAssets = (filters: MediaFilter = {}): Promise<MediaAsset[]> => {
  const params = new URLSearchParams()
  if (filters.product_id) params.set('product_id', filters.product_id)
  if (filters.order_line_id) params.set('order_line_id', filters.order_line_id)
  if (filters.cad_file_id) params.set('cad_file_id', filters.cad_file_id)
  if (filters.asset_types?.length) filters.asset_types.forEach(t => params.append('asset_types', t))
  if (filters.skip !== undefined) params.set('skip', String(filters.skip))
  if (filters.limit !== undefined) params.set('limit', String(filters.limit))
  if (filters.sort_by) params.set('sort_by', filters.sort_by)
  if (filters.sort_dir) params.set('sort_dir', filters.sort_dir)
  return api.get(`/media/?${params}`).then(r => r.data)
}

export const getMediaAsset = (id: string): Promise<MediaAsset> =>
  api.get(`/media/${id}`).then(r => r.data)

export const downloadMediaAsset = (id: string): void => {
  window.open(`/api/media/${id}/download`, '_blank')
}

export const zipDownloadAssets = (ids: string[]): Promise<void> =>
  api.post('/media/zip', ids, { responseType: 'blob' }).then(r => {
    const url = URL.createObjectURL(r.data)
    const a = document.createElement('a')
    a.href = url
    a.download = 'media-export.zip'
    a.click()
    setTimeout(() => URL.revokeObjectURL(url), 100)
  })

export const archiveMediaAsset = (id: string): Promise<void> =>
  api.delete(`/media/${id}`).then(() => undefined)

export const deleteMediaAssetPermanent = (id: string): Promise<void> =>
  api.delete(`/media/${id}/permanent`).then(() => undefined)
