import { api, BASE_URL, authHeaders } from './client'

export function fetchActiveEncounters(department, { page = 1, pageSize = 20 } = {}) {
  const params = new URLSearchParams({
    status: 'ACTIVE',
    page: String(page),
    pageSize: String(pageSize),
  })
  if (department) params.set('department', department)
  return api.get(`/api/v1/encounters?${params}`)
}

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

  do {
    const data = await fetchActiveEncounters(department, { page, pageSize: 100 })
    items.push(...(data.items ?? []))
    totalCount = data.totalCount ?? items.length
    page += 1
  } while (items.length < totalCount)

  return items
}

export function fetchEncounter(id) {
  return api.get(`/api/v1/encounters/${id}`)
}

export async function fetchObservations(encounterId, { limit = 50 } = {}) {
  const all = []
  let cursor = null
  do {
    const params = new URLSearchParams({ limit: String(limit) })
    if (cursor) params.set('cursor', cursor)
    const page = await api.get(`/api/v1/encounters/${encounterId}/observations?${params}`)
    all.push(...(page.items ?? []))
    cursor = page.hasMore ? page.nextCursor : null
  } while (cursor)
  return all
}

export function fetchTimeline(encounterId) {
  return api.get(`/api/v1/encounters/${encounterId}/timeline`)
}

export function submitVitalsObservations(encounterId, observations) {
  return api.post(`/api/v1/encounters/${encounterId}/observations`, {
    observations,
  })
}

export function fetchDischargeSummaryStatus(encounterId) {
  return api.get(`/api/v1/encounters/${encounterId}/discharge-summary`)
}

export async function fetchDischargeSummaryContent(encounterId) {
  const res = await fetch(
    `${BASE_URL}/api/v1/encounters/${encounterId}/discharge-summary/content`,
    { headers: authHeaders() },
  )
  if (res.status === 404) {
    const envelope = await res.json().catch(() => null)
    const code = envelope?.error?.code
    if (code === 'DISCHARGE_SUMMARY_PENDING') return null
    throw new Error(envelope?.error?.message ?? 'Discharge summary not found.')
  }
  if (res.status === 401) {
    throw new Error('Session expired — please log in again.')
  }
  if (!res.ok) {
    const envelope = await res.json().catch(() => null)
    throw new Error(envelope?.error?.message ?? `Failed to download discharge summary (${res.status})`)
  }
  return res.text()
}