import { api } from './client'

export function fetchAlertById(alertId) {
  return api.get(`/api/v1/alerts/${alertId}`)
}

export function fetchAlerts(encounterId, status) {
  const params = new URLSearchParams()
  if (status) params.set('status', status)
  return api.get(`/api/v1/encounters/${encounterId}/alerts?${params}`)
}

export function fetchAllAlerts(status) {
  const params = new URLSearchParams()
  if (status) params.set('status', status)
  return api.get(`/api/v1/alerts?${params}`)
}

export async function fetchAllOpenAlerts() {
  const items = []
  let page = 1
  let totalCount = 0

  do {
    const params = new URLSearchParams({
      status: 'OPEN',
      page: String(page),
      pageSize: '100',
    })
    const data = await api.get(`/api/v1/alerts?${params}`)
    items.push(...(data.items ?? []))
    totalCount = data.totalCount ?? items.length
    page += 1
  } while (items.length < totalCount)

  return items
}

export function acknowledgeAlert(alertId, note) {
  return api.post(`/api/v1/alerts/${alertId}/acknowledge`, { note })
}

export function resolveAlert(alertId) {
  return api.post(`/api/v1/alerts/${alertId}/resolve`)
}