/**
 * ABGABE-STATUS: API client for the reservation/sale-status pipeline (/reservations).
 * Status verfügbar → reserviert → abgegeben. This is the informal pre-handover status —
 * separate from the legal Vertrag (SaleContract).
 */
import { api } from './client'

const RESOURCE = '/reservations'

/** Canonical status values (match the backend contract, case-sensitive). */
export type ReservationStatus = 'verfuegbar' | 'reserviert' | 'abgegeben'

export interface SaleReservation {
  id: string
  gerbilId: string
  gerbilName: string | null
  status: ReservationStatus
  reservedForContactId: string | null
  contactName: string | null
  /** ISO-8601 appointment date or null. */
  appointmentDate: string | null
  price: number | null
  note: string | null
  /** ISO-8601 hand-over date or null. */
  handedOverDate: string | null
  createdAt: string
  updatedAt: string
}

/** Payload for POST /reservations. */
export interface CreateReservation {
  gerbilId: string
  gerbilName?: string | null
  status?: ReservationStatus
  reservedForContactId?: string | null
  contactName?: string | null
  appointmentDate?: string | null
  price?: number | null
  note?: string | null
  handedOverDate?: string | null
}

/** Payload for PUT /reservations/{id}. */
export type UpdateReservation = Partial<Omit<CreateReservation, 'gerbilId'>>

/** List all reservations, newest-updated first. */
export function listReservations(): Promise<SaleReservation[]> {
  return api.get<SaleReservation[]>(RESOURCE)
}

/** List the reservation status rows for one animal. */
export function listReservationsForGerbil(gerbilId: string): Promise<SaleReservation[]> {
  return api.get<SaleReservation[]>(`${RESOURCE}?gerbilId=${encodeURIComponent(gerbilId)}`)
}

export function createReservation(body: CreateReservation): Promise<SaleReservation> {
  return api.post<SaleReservation>(RESOURCE, body)
}

export function updateReservation(id: string, body: UpdateReservation): Promise<SaleReservation> {
  return api.put<SaleReservation>(`${RESOURCE}/${id}`, body)
}

export function deleteReservation(id: string): Promise<void> {
  return api.delete(`${RESOURCE}/${id}`)
}
