import api from './client'

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

// ── Media Browser (server-side filtered + paginated) ──────────────────────────

export interface MediaAssetFilters {
  asset_type?: string
  category_key?: string
  render_status?: string
  q?: string
  exclude_technical?: boolean
  page?: number
  page_size?: number
}

export interface MediaAssetItem {
  id: string
  asset_type: MediaAssetType
  file_path: string
  file_size_bytes: number | null
  mime_type: string | null
  created_at: string
  order_line_id: string | null
  product_id: string | null
  product_name: string | null
  product_pim_id: string | null
  category_key: string | null
  render_status: string | null
  // Extended product metadata
  product_ebene1: string | null
  product_ebene2: string | null
  product_baureihe: string | null
  product_produkt_baureihe: string | null
  product_lagertyp: string | null
  product_name_cad_modell: string | null
  download_url: string | null
  thumbnail_url: string | null
}

export interface MediaAssetListResponse {
  items: MediaAssetItem[]
  total: number
  page: number
  page_size: number
  pages: number
}

export function getMediaAssets(filters: MediaAssetFilters = {}): Promise<MediaAssetListResponse> {
  const params = new URLSearchParams()
  if (filters.asset_type) params.set('asset_type', filters.asset_type)
  if (filters.category_key) params.set('category_key', filters.category_key)
  if (filters.render_status) params.set('render_status', filters.render_status)
  if (filters.q) params.set('q', filters.q)
  if (filters.exclude_technical !== undefined) params.set('exclude_technical', String(filters.exclude_technical))
  if (filters.page !== undefined) params.set('page', String(filters.page))
  if (filters.page_size !== undefined) params.set('page_size', String(filters.page_size))
  return api.get(`/media/assets?${params}`).then(r => r.data)
}

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 listMediaAssets = (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)

export const batchDeleteAssets = (ids: string[]): Promise<{ deleted: number; requested: number }> =>
  api.post('/media/batch-delete', ids).then(r => r.data)
