import client from "./client"
import type { ApiResponse } from "../types"

export interface RechargeCreateResponse {
  out_trade_no: string
  amount: number
  payment_plugin: string | null
  payment_method: string | null
  payment_name: string | null
  payurl: string | null
  qrcode: string | null
  urlscheme: string | null
  trade_no: string | null
}

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

export interface RechargeQueryResult {
  out_trade_no: string
  status: "pending" | "paid" | "expired" | "closed" | "refunded"
  paid: boolean
  balance: number | null
}

export interface PendingRechargePayment {
  out_trade_no: string
  amount: number
  payment_plugin: string | null
  payment_method: string | null
  payment_name: string | null
  payurl: string | null
  qrcode: string | null
  urlscheme: string | null
  trade_no: string | null
  expires_at: string
}

export interface RechargePaymentOption {
  id: string
  name: string
  description: string
  method: string
  method_label: string
  capabilities: string[]
}

export async function listRechargePaymentOptions() {
  const { data } = await client.get<ApiResponse<RechargePaymentOption[]>>("/v1/recharge/payment-options")
  return data
}

export async function createRecharge(amount: number, payment_plugin?: string) {
  const { data } = await client.post<ApiResponse<RechargeCreateResponse>>(
    "/v1/recharge",
    { amount, payment_plugin },
    { timeout: 30000 },
  )
  return data
}

export async function getPendingRecharge() {
  const { data } = await client.get<ApiResponse<PendingRechargePayment | null>>("/v1/recharge/pending")
  return data
}

export async function pollRechargeStatus(out_trade_no: string) {
  const { data } = await client.get<ApiResponse<RechargeQueryResult>>(
    `/v1/recharge/status/${out_trade_no}`,
  )
  return data
}

export async function listRechargeOrders(limit = 20, offset = 0) {
  const { data } = await client.get<ApiResponse<RechargeOrder[] | { items?: RechargeOrder[]; total?: number }>>(
    `/v1/recharge/orders?limit=${limit}&offset=${offset}`,
  )
  if (Array.isArray(data.data)) {
    return data as ApiResponse<RechargeOrder[]>
  }
  return {
    ...data,
    data: Array.isArray(data.data?.items) ? data.data.items : [],
  } as ApiResponse<RechargeOrder[]>
}
