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

const RESOURCE = '/weight-records'

export interface WeightRecord {
  id: string
  gerbilId: string
  date: DateOnlyString
  weightGrams: number
  notes: string | null
}

/** Payload for POST /weight-records. */
export interface CreateWeightRecord {
  gerbilId: string
  date: DateOnlyString
  weightGrams: number
  notes?: string | null
}

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

export function createWeightRecord(body: CreateWeightRecord): Promise<WeightRecord> {
  return api.post<WeightRecord>(RESOURCE, body)
}

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