import { apiRequest, getAccessToken, HttpError } from '@/shared/api/client'
import type { CreatedIdResponse, ImageCategory, ImageDto } from '@/shared/api/types'

export function listImages(category: ImageCategory) {
  const q = new URLSearchParams({ category })
  return apiRequest<ImageDto[]>(`/admin/images?${q.toString()}`)
}

export function deleteImage(id: string) {
  return apiRequest<void>(`/admin/images/${id}`, { method: 'DELETE' })
}

/** Публичный URL файла изображения (для <img>). */
export function imageUrl(id: string) {
  return `/api/images/${id}`
}

/** Загрузка изображения в категорию (сырое тело, имя/категория в query — как uploadMedia). */
export function uploadImage(category: ImageCategory, file: File): Promise<CreatedIdResponse> {
  return new Promise((resolve, reject) => {
    const xhr = new XMLHttpRequest()
    const q = new URLSearchParams({ fileName: file.name, category })
    xhr.open('POST', `/api/admin/images?${q.toString()}`)
    const token = getAccessToken()
    if (token) xhr.setRequestHeader('Authorization', `Bearer ${token}`)
    xhr.onload = () => {
      if (xhr.status >= 200 && xhr.status < 300) {
        try {
          resolve(JSON.parse(xhr.responseText) as CreatedIdResponse)
        } catch {
          reject(new HttpError({ title: 'Bad response' }, xhr.status))
        }
      } else {
        let detail = `HTTP ${xhr.status}`
        try {
          const p = JSON.parse(xhr.responseText) as { detail?: string; title?: string }
          detail = p.detail ?? p.title ?? detail
        } catch {
          /* пусто */
        }
        reject(new HttpError({ detail }, xhr.status))
      }
    }
    xhr.onerror = () => reject(new HttpError({ title: 'Network error' }, 0))
    xhr.send(file)
  })
}
