import { apiClient } from '@/shared/api/client'

import type { ApiResponse, PaginatedResult } from '@/shared/types/types'

export interface AdminPayment {
  id: number
  payment_no: string
  order_id: number
  order_no: string
  user_id: number
  user_phone: string
  provider: string
  merchant_id: string
  third_order_id: string
  provider_order_id: string
  pay_way: string
  amount_cent: number
  biz_type: string
  status: string
  error_code: string
  error_message: string
  raw_request?: Record<string, unknown>
  raw_response?: Record<string, unknown>
  paid_at?: string
  notified_at?: string
  created_at: string
  updated_at: string
}

export interface AdminPaymentQuery {
  user_id?: string
  order_id?: string
  order_no?: string
  biz_type?: string
  status?: string
  provider?: string
  page?: number
  page_size?: number
}

export async function fetchAdminPayments(query: AdminPaymentQuery = {}) {
  const params = Object.fromEntries(
    Object.entries(query).filter(([, value]) => value !== '' && value !== undefined)
  )
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<AdminPayment>>>(
    '/admin/payments',
    { params }
  )
  const result = data.data
  return {
    items: Array.isArray(result?.items) ? result.items : [],
    total: Number(result?.total ?? 0),
    page: Number(result?.page ?? query.page ?? 1),
    page_size: Number(result?.page_size ?? query.page_size ?? 20),
  }
}
