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

import type { ApiResponse, PaginatedResult } from '@/shared/types/types'
import type { BalanceType, LedgerDirection, WalletStatus } from '@/shared/types/status'
import type { PaymentOrder } from '@/features/orders/api/orders'

export interface WalletAccount {
  user_id: number
  available_balance: number
  frozen_balance: number
  status: WalletStatus
}

export interface WalletLedger {
  id: number
  ledger_no: string
  user_id: number
  order_id?: number
  direction: LedgerDirection
  amount: number
  balance_after: number
  balance_type: BalanceType
  biz_type: string
  biz_no: string
  remark: string
  created_at: string
}

export async function fetchWalletBalance() {
  const { data } = await apiClient.get<ApiResponse<WalletAccount>>('/wallet/balance')
  return data.data
}

export async function fetchWalletLedger(page = 1, pageSize = 20) {
  const { data } = await apiClient.get<ApiResponse<PaginatedResult<WalletLedger>>>('/wallet/ledger', {
    params: { page, page_size: pageSize },
  })
  return data.data
}

export async function rechargeWallet(amount: number) {
  const { data } = await apiClient.post<ApiResponse<WalletAccount>>('/wallet/recharge', { amount })
  return data.data
}

export async function startWalletRechargePayment(amount: number) {
  const { data } = await apiClient.post<ApiResponse<PaymentOrder>>('/wallet/recharge/pay', { amount })
  return data.data
}

export async function queryWalletRechargePayment(id: number) {
  const { data } = await apiClient.post<ApiResponse<PaymentOrder>>(`/wallet/recharge/pay/${id}/query`)
  return data.data
}
