/** Fotos für Gehege (Enclosure) — analog zu api/photos, gleiche Dateiablage. */
import { API_BASE_URL, ApiError, api } from './client'
import { de } from '../strings/de'
import { photoSrc, type GerbilPhoto } from './photos'

/** Identical shape to a gerbil photo (PhotoDto). */
export type EnclosurePhoto = GerbilPhoto

export function listEnclosurePhotos(enclosureId: string): Promise<EnclosurePhoto[]> {
  return api.get<EnclosurePhoto[]>(`/enclosures/${enclosureId}/photos`)
}

export async function uploadEnclosurePhoto(
  enclosureId: string,
  file: File,
  caption: string | null,
): Promise<EnclosurePhoto> {
  const form = new FormData()
  form.append('file', file)
  if (caption) form.append('caption', caption)

  let response: Response
  try {
    response = await fetch(`${API_BASE_URL}/enclosures/${enclosureId}/photos`, {
      method: 'POST',
      body: form,
    })
  } catch {
    throw new ApiError(de.api.errors.network, null)
  }
  if (!response.ok) {
    const message =
      response.status === 404
        ? de.api.errors.notFound
        : response.status >= 500
          ? de.api.errors.server
          : de.api.errors.unknown
    throw new ApiError(message, response.status)
  }
  return (await response.json()) as EnclosurePhoto
}

export function deleteEnclosurePhoto(photoId: string): Promise<void> {
  return api.delete(`/enclosure-photos/${photoId}`)
}

export { photoSrc }
