import { api, type ApiEnvelope, unwrapApiData } from '@/lib/api'
import { type PageResult } from '@/features/admin/api'
import { type ApiCallLog } from '@/features/third-party/api'

export type OrderLogType = 'normal' | 'zhs' | 'yjy' | 'stream'

export type OrderLogQueryResult = {
  provider: string
  type: OrderLogType
  act: string
  orderId: string
  queriedAt: string
  response: unknown
  entries: unknown[]
}

export function queryOrderLog(data: {
  orderId: string
  type: OrderLogType
}) {
  const endpoint =
    data.type === 'stream'
      ? '/api/admin/order-logs/stream'
      : '/api/admin/order-logs/query'
  return api
    .post<OrderLogQueryResult | ApiEnvelope<OrderLogQueryResult>>(endpoint, data)
    .then((response) => unwrapApiData(response.data))
}

export function listOrderLogHistory(params: {
  page: number
  pageSize: number
  orderId?: string
  type?: string
  status?: string
}) {
  return api
    .get<PageResult<ApiCallLog> | ApiEnvelope<PageResult<ApiCallLog>>>(
      '/api/admin/order-logs/history',
      { params }
    )
    .then((response) => unwrapApiData(response.data))
}
