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

export interface AdminRechargeOrder {
  id: number
  user_id: number
  out_trade_no: string
  trade_no: string | null
  channel: string
  amount: number
  amount_cents: number
  status: "pending" | "paid" | "expired" | "closed" | "refunded"
  remark: string | null
  created_at: string
  updated_at: string
}

export interface AdminRechargeStats {
  total_paid_count: number
  total_paid_cents: number
  today_paid_count: number
  today_paid_cents: number
  pending_count: number
}

export interface AdminBalanceLog {
  id: number
  user_id: number
  change_type: string
  delta: number
  balance_after: number
  ref_no: string | null
  operator_id: number | null
  remark: string | null
  created_at: string
}

export async function listAdminRechargeOrders(params: {
  keyword?: string
  status?: string
  channel?: string
  limit?: number
  offset?: number
}) {
  const p = new URLSearchParams()
  if (params.keyword) p.set("keyword", params.keyword)
  if (params.status) p.set("status", params.status)
  if (params.channel) p.set("channel", params.channel)
  if (params.limit != null) p.set("limit", String(params.limit))
  if (params.offset != null) p.set("offset", String(params.offset))
  const { data } = await adminClient.get<ApiResponse<AdminRechargeOrder[] | { items: AdminRechargeOrder[]; total: number }>>(
    `/v1/admin/finance/recharge-orders?${p.toString()}`,
  )
  return { ...data, data: listResult<AdminRechargeOrder>(data.data) }
}

export async function getAdminRechargeStats() {
  const { data } = await adminClient.get<ApiResponse<AdminRechargeStats>>(
    "/v1/admin/finance/recharge-orders/stats",
  )
  return data
}

export async function listAdminBalanceLogs(params: {
  user_id?: number
  change_type?: string
  limit?: number
  offset?: number
}) {
  const p = new URLSearchParams()
  if (params.user_id) p.set("user_id", String(params.user_id))
  if (params.change_type) p.set("change_type", params.change_type)
  if (params.limit != null) p.set("limit", String(params.limit))
  if (params.offset != null) p.set("offset", String(params.offset))
  const { data } = await adminClient.get<ApiResponse<AdminBalanceLog[] | { items: AdminBalanceLog[]; total: number }>>(
    `/v1/admin/finance/balance-logs?${p.toString()}`,
  )
  return { ...data, data: listResult<AdminBalanceLog>(data.data) }
}
