/**
 * 交易 API 客户端
 * 提供转账、充值、提现等交易功能
 */
import { apiClient } from './client'
import type { 
  SystemTransaction, 
  BankTransaction, 
  TransactionQuery, 
  TransactionListResponse,
  CreateTransactionRequest,
  TransferRequest,
  TransferResponse 
} from '@/types/transaction'
import type { PageResponse } from '@/types/api'

/**
 * 充值请求
 */
export interface DepositRequest {
  account_id: number
  amount: string
  source_key?: string
  remark?: string
}

/**
 * 提现请求
 */
export interface WithdrawRequest {
  account_id: number
  amount: string
  remark?: string
}

export class TransactionAPI {
  // ==================== 核心交易操作 ====================
  
  /**
   * 发起转账
   * 对应后端: POST /api/v1/transactions/transfer
   */
  static async transfer(data: TransferRequest): Promise<SystemTransaction> {
    return apiClient.post('/transactions/transfer', data)
  }

  /**
   * 发起充值 (入金)
   * 对应后端: POST /api/v1/transactions/deposit
   */
  static async deposit(data: DepositRequest): Promise<SystemTransaction> {
    return apiClient.post('/transactions/deposit', data)
  }

  /**
   * 发起提现 (出金)
   * 对应后端: POST /api/v1/transactions/withdraw
   */
  static async withdraw(data: WithdrawRequest): Promise<SystemTransaction> {
    return apiClient.post('/transactions/withdraw', data)
  }

  // ==================== 交易查询 ====================

  /**
   * 获取交易详情
   * 对应后端: GET /api/v1/transactions/:id
   */
  static async getTransaction(id: number): Promise<SystemTransaction> {
    return apiClient.get(`/transactions/${id}`)
  }
  
  /**
   * 获取交易列表
   * 对应后端: GET /api/v1/transactions
   */
  static async getTransactions(query: TransactionQuery = {}): Promise<PageResponse<SystemTransaction>> {
    return apiClient.get('/transactions', { params: query })
  }

  // ==================== 兼容旧方法 (保持向后兼容) ====================

  /**
   * @deprecated 使用 getTransactions 替代
   */
  static async getTransactionList(query: TransactionQuery = {}): Promise<TransactionListResponse> {
    return apiClient.get('/transactions', { params: query })
  }
  
  /**
   * 根据交易号获取交易 (需要后端支持)
   * 注意: 当前后端未提供此端点，需要使用 getTransactions + filter
   */
  static async getTransactionByNo(txnNo: string): Promise<SystemTransaction> {
    const result = await this.getTransactions({ txn_no: txnNo })
    if (result.data && result.data.length > 0) {
      return result.data[0]
    }
    throw new Error('交易不存在')
  }

  // ==================== 扩展功能 (需要后端支持) ====================

  /**
   * 创建交易 (通用)
   * 注意: 建议使用具体的 transfer/deposit/withdraw 方法
   */
  static async createTransaction(data: CreateTransactionRequest): Promise<SystemTransaction> {
    // 根据交易类型调用对应的方法
    switch (data.txn_type) {
      case 'transfer':
        return this.transfer({
          from_account_id: data.from_account_id!,
          to_account_id: data.to_account_id!,
          amount: data.amount,
          remark: data.remark,
        })
      case 'deposit':
        return this.deposit({
          account_id: data.to_account_id!,
          amount: data.amount,
          remark: data.remark,
        })
      case 'withdrawal':
        return this.withdraw({
          account_id: data.from_account_id!,
          amount: data.amount,
          remark: data.remark,
        })
      default:
        throw new Error(`不支持的交易类型: ${data.txn_type}`)
    }
  }
  
  /**
   * 提交交易到银行 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async submitToBank(id: number): Promise<{ bankRefNo: string }> {
    return apiClient.post(`/transactions/${id}/submit`)
  }
  
  /**
   * 取消交易 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async cancelTransaction(id: number): Promise<void> {
    return apiClient.post(`/transactions/${id}/cancel`)
  }
  
  /**
   * 重试交易 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async retryTransaction(id: number): Promise<SystemTransaction> {
    return apiClient.post(`/transactions/${id}/retry`)
  }
  
  /**
   * 获取交易状态 (需要后端扩展)
   * 注意: 可以通过 getTransaction 获取完整信息
   */
  static async getTransactionStatus(id: number): Promise<{ status: string, bankRefNo?: string }> {
    const txn = await this.getTransaction(id)
    return {
      status: txn.status,
      bankRefNo: txn.bank_ref_no,
    }
  }
  
  /**
   * 查询银行流水 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async getBankStatements(params: {
    accountNo: string
    startDate: string
    endDate: string
    page?: number
    pageSize?: number
  }): Promise<{
    items: BankTransaction[]
    total: number
  }> {
    return apiClient.get('/bank/statements', { params })
  }
  
  /**
   * 查询交易统计 (需要后端扩展)
   * @todo 后端需要添加此端点
   */
  static async getTransactionStats(params: {
    accountId?: number
    startDate?: string
    endDate?: string
  }): Promise<{
    totalCount: number
    totalAmount: number
    successCount: number
    failedCount: number
    pendingCount: number
  }> {
    return apiClient.get('/transactions/stats', { params })
  }
  
  /**
   * 获取账户交易历史（分页）
   * 使用 getTransactions + from_account_id 筛选
   */
  static async getTransactionHistory(params: {
    accountId: number
    page?: number
    pageSize?: number
    startDate?: string
    endDate?: string
  }): Promise<PageResponse<SystemTransaction>> {
    return this.getTransactions({
      from_account_id: params.accountId,
      page: params.page,
      page_size: params.pageSize,
      start_date: params.startDate,
      end_date: params.endDate,
    })
  }
}

export default TransactionAPI
