import type { PipelineRun } from '../types/pipeline'

async function readJson<T>(response: Response, message: string): Promise<T> {
  if (!response.ok) {
    const detail = await response.text()
    throw new Error(`${message}: ${response.status} ${detail || response.statusText}`)
  }
  return response.json() as Promise<T>
}

export async function fetchPipelineRuns(): Promise<{ items: PipelineRun[] }> {
  return readJson(await fetch('/api/pipeline/runs'), '加载流水线批次失败')
}

export async function fetchPipelineRun(runId: string): Promise<PipelineRun> {
  return readJson(
    await fetch(`/api/pipeline/runs/${encodeURIComponent(runId)}`),
    '加载流水线详情失败',
  )
}

export async function createPipelineRun(bizDt: string): Promise<{
  accepted: boolean
  run_id: string
  status: string
}> {
  return readJson(
    await fetch('/api/pipeline/runs', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ biz_dt: bizDt || null }),
    }),
    '创建流水线批次失败',
  )
}

export async function resumePipelineRun(runId: string): Promise<void> {
  await readJson(
    await fetch(`/api/pipeline/runs/${encodeURIComponent(runId)}/resume`, {
      method: 'POST',
    }),
    '恢复流水线失败',
  )
}

export async function cancelPipelineRun(runId: string): Promise<void> {
  await readJson(
    await fetch(`/api/pipeline/runs/${encodeURIComponent(runId)}/cancel`, {
      method: 'POST',
    }),
    '取消流水线失败',
  )
}
