export interface SchedulerJobStatus {
  id: string
  name: string
  next_run_time: string | null
}

export interface SchedulerStatus {
  enabled: boolean
  running: boolean | null
  timezone: string
  jobs: SchedulerJobStatus[]
}

export interface ManualJob {
  id: string
  name: string
  description: string
  accepts_biz_dt: boolean
  accepts_partition_date: boolean
}

export interface ManualRun {
  accepted?: boolean
  run_id: string
  job_id?: string
  job_name?: string
  status: 'queued' | 'running' | 'succeeded' | 'failed' | 'blocked_previous_run' | string
  biz_dt: string
  partition_date?: string | null
  started_at?: string
  finished_at?: string
  error?: string
  error_message?: string
}

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

export async function fetchHealth(): Promise<{ status: string }> {
  return readJson(await fetch('/health'), '服务健康检查失败')
}

export async function fetchSchedulerStatus(): Promise<SchedulerStatus> {
  return readJson(await fetch('/api/scheduler/status'), '加载调度器状态失败')
}

export async function fetchManualJobs(): Promise<{ items: ManualJob[] }> {
  return readJson(await fetch('/api/scheduler/jobs'), '加载任务列表失败')
}

export async function runManualJob(jobId: string, bizDt: string): Promise<ManualRun> {
  return readJson(
    await fetch(`/api/scheduler/jobs/${encodeURIComponent(jobId)}/run`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ biz_dt: bizDt || null, wait: false }),
    }),
    '任务启动失败',
  )
}

export async function fetchManualRun(runId: string): Promise<ManualRun> {
  return readJson(
    await fetch(`/api/scheduler/runs/${encodeURIComponent(runId)}`),
    '加载运行状态失败',
  )
}
