import adminClient from "./client"
import type { ApiResponse } from "../../types"
import type { UpstreamActionLog } from "../../api/upstreamActions"
import { listResult } from "./response"

export interface UpstreamActionFilters {
  keyword?: string
  status?: string
  source?: string
  action_type?: string
  user_id?: number
  order_id?: number
  instance_id?: number
  limit?: number
  offset?: number
}

export interface UpstreamActionSyncSummary {
  checked: number
  success: number
  failed: number
  running: number
  errored: number
}

export async function listAdminUpstreamActions(params: UpstreamActionFilters) {
  const p = new URLSearchParams()
  Object.entries(params).forEach(([key, value]) => {
    if (value !== undefined && value !== null && value !== "") p.set(key, String(value))
  })
  const { data } = await adminClient.get<ApiResponse<UpstreamActionLog[] | { items: UpstreamActionLog[]; total: number }>>(
    `/v1/admin/upstream-actions?${p.toString()}`,
  )
  return { ...data, data: listResult<UpstreamActionLog>(data.data) }
}

export async function syncAdminUpstreamActions() {
  const { data } = await adminClient.post<ApiResponse<UpstreamActionSyncSummary>>(
    "/v1/admin/upstream-actions/sync",
  )
  return data
}

export async function syncAdminUpstreamAction(actionId: number) {
  const { data } = await adminClient.post<ApiResponse<UpstreamActionLog>>(
    `/v1/admin/upstream-actions/${actionId}/sync`,
  )
  return data
}

export async function retryAdminUpstreamAction(actionId: number, remark?: string) {
  const { data } = await adminClient.post<ApiResponse<{
    new_action_log_id: number
    status: string
    taskid: number | null
  }>>(`/v1/admin/upstream-actions/${actionId}/retry`, { remark })
  return data
}

export async function markAdminUpstreamActionHandled(actionId: number, remark?: string) {
  const { data } = await adminClient.post<ApiResponse<UpstreamActionLog>>(
    `/v1/admin/upstream-actions/${actionId}/mark-handled`,
    { remark },
  )
  return data
}

export async function ignoreAdminUpstreamAction(actionId: number, remark?: string) {
  const { data } = await adminClient.post<ApiResponse<UpstreamActionLog>>(
    `/v1/admin/upstream-actions/${actionId}/ignore`,
    { remark },
  )
  return data
}
