import adminClient from "./client"
import type { ApiResponse } from "../../types"
import { listResult, pageResult } from "./response"

const BASE = "/v1/admin/tasks"

export interface TaskRunLog {
  id: number
  task_key: string
  task_name: string
  trigger_type: string
  status: string
  operator_id: number | null
  started_at: string | null
  finished_at: string | null
  duration_ms: number | null
  summary: Record<string, unknown> | null
  error_message: string | null
  created_at: string | null
}

export interface TaskItem {
  key: string
  name: string
  group: string
  description: string
  manual_enabled: boolean
  interval_label: string
  running: boolean
  latest_run: TaskRunLog | null
  failed_runs: number
}

export async function listTasks(): Promise<ApiResponse<TaskItem[]>> {
  const { data } = await adminClient.get<ApiResponse<TaskItem[] | { items: TaskItem[]; total: number }>>(BASE)
  return { ...data, data: listResult<TaskItem>(data.data) }
}

export async function listTaskRuns(params?: {
  task_key?: string
  status?: string
  trigger_type?: string
  offset?: number
  limit?: number
}): Promise<ApiResponse<{ items: TaskRunLog[]; total: number }>> {
  const { data } = await adminClient.get<ApiResponse<{ items: TaskRunLog[]; total: number } | TaskRunLog[]>>(`${BASE}/runs`, { params })
  return { ...data, data: pageResult<TaskRunLog>(data.data) }
}

export async function runTask(taskKey: string): Promise<ApiResponse<{ accepted: boolean; status: string; task_key: string; summary?: Record<string, unknown>; reason?: string }>> {
  const { data } = await adminClient.post<ApiResponse<{ accepted: boolean; status: string; task_key: string; summary?: Record<string, unknown>; reason?: string }>>(`${BASE}/${taskKey}/run`)
  return data
}
