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

export type ThirdPartyConfigStatus = {
  provider: string
  baseUrl: string | null
  uidConfigured: boolean
  keyConfigured: boolean
  debugLogEnabled: boolean
}

export type ApiCallLog = {
  id: string
  provider: string
  act: string
  method: string
  url: string
  status: 'success' | 'failure'
  success: boolean
  httpStatus: number | null
  durationMs: number | null
  requestPayload: Record<string, unknown> | null
  responsePayload: unknown | null
  errorMessage: string | null
  createdAt: string
}

export type ConnectionTestResult = {
  provider: string
  act: string
  connected: boolean
  response: unknown
}

export type ThirdPartyOrderListSyncResult = {
  provider: string
  total: number
  matched: number
  created: number
  updated: number
  imported: number
  localUpdated: number
  unmatched: number
  page: number
  limit: number
  recent: number
}

export function getThirdPartyConfigStatus() {
  return api
    .get<
      ThirdPartyConfigStatus | ApiEnvelope<ThirdPartyConfigStatus>
    >('/api/admin/third-party/config-status')
    .then((response) => unwrapApiData(response.data))
}

export function testThirdPartyConnection() {
  return api
    .post<
      ConnectionTestResult | ApiEnvelope<ConnectionTestResult>
    >('/api/admin/third-party/test-connection')
    .then((response) => unwrapApiData(response.data))
}

export function listApiCallLogs(params: {
  page: number
  pageSize: number
  keyword?: string
  act?: string
  status?: string
  provider?: string
}) {
  return api
    .get<PageResult<ApiCallLog> | ApiEnvelope<PageResult<ApiCallLog>>>(
      '/api/admin/third-party/api-call-logs',
      { params }
    )
    .then((response) => unwrapApiData(response.data))
}

export function syncThirdPartyOrderList(data: {
  page?: number
  limit?: number
  recent?: number
} = {}) {
  return api
    .post<
      | ThirdPartyOrderListSyncResult
      | ApiEnvelope<ThirdPartyOrderListSyncResult>
    >('/api/admin/third-party/orders/sync', data)
    .then((response) => unwrapApiData(response.data))
}
