/** Typed API functions for the Gesundheit (HealthRecord) resource. (FEAT-6) */
import { api } from './client'
import { condition, toQueryString } from './gridify'
import type { DateOnlyString, Paged } from './types'

const RESOURCE = '/health-records'

/** HealthRecord.Type — C# enum member names (JsonStringEnumConverter). */
export type HealthRecordType =
  | 'Examination'
  | 'Treatment'
  | 'Injury'
  | 'Vaccination'
  | 'Other'
export const HEALTH_RECORD_TYPES: HealthRecordType[] = [
  'Examination',
  'Treatment',
  'Injury',
  'Vaccination',
  'Other',
]

export interface HealthRecord {
  id: string
  gerbilId: string
  date: DateOnlyString
  type: HealthRecordType
  description: string
  veterinarian: string | null
  createdAt: string
}

/** Payload for POST /health-records. */
export interface CreateHealthRecord {
  gerbilId: string
  date: DateOnlyString
  type: HealthRecordType
  description: string
  veterinarian?: string | null
}

/** Payload for PUT /health-records/{id}. */
export type UpdateHealthRecord = Partial<CreateHealthRecord>

/** Alle Einträge eines Tieres, neueste zuerst. */
export async function listHealthRecords(gerbilId: string): Promise<HealthRecord[]> {
  const paged = await api.get<Paged<HealthRecord>>(
    `${RESOURCE}${toQueryString({
      filter: condition({ field: 'gerbilId', op: '==', value: gerbilId }),
      orderBy: 'date desc',
      page: 1,
      pageSize: 500,
    })}`,
  )
  return paged.items
}

export function createHealthRecord(body: CreateHealthRecord): Promise<HealthRecord> {
  return api.post<HealthRecord>(RESOURCE, body)
}

export function updateHealthRecord(id: string, body: UpdateHealthRecord): Promise<HealthRecord> {
  return api.put<HealthRecord>(`${RESOURCE}/${id}`, body)
}

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