import { apiClient } from '@/lib/api/client';
import type { SystemConfig } from '@/types/config';

export interface ContributionSyncStatus {
  isSynced: boolean;
  miningNetworkTotal: string;
  networkTotalContribution: string;
}

export interface PoolAccountInfo {
  walletName: string;
  name: string;
  walletPoolType: string;
  blockchainPoolType: string;
}

export interface PoolAccountBalance {
  walletName: string;
  walletAddress: string;
  balance: string;
  availableBalance: string;
  frozenBalance: string;
  threshold: string;
  lastUpdated?: string;
}

export interface MiningStatus {
  initialized: boolean;
  isActive: boolean;
  activatedAt?: string;
  currentEra: number;
  remainingDistribution: string;
  secondDistribution: string;
  accountCount: number;
  totalContribution: string;
  contributionSyncStatus?: ContributionSyncStatus;
  error?: string;
}

export const configsApi = {
  getAll: async (): Promise<SystemConfig[]> => {
    const response = await apiClient.get('/configs');
    return response.data.data;
  },

  update: async (key: string, value: string): Promise<SystemConfig> => {
    const response = await apiClient.put(`/configs/${key}`, { value });
    return response.data.data;
  },

  getTransferEnabled: async (): Promise<boolean> => {
    const response = await apiClient.get('/configs/transfer-enabled');
    return response.data.data.enabled;
  },

  setTransferEnabled: async (enabled: boolean): Promise<void> => {
    await apiClient.post('/configs/transfer-enabled', { enabled });
  },

  getMiningStatus: async (): Promise<MiningStatus> => {
    const response = await apiClient.get('/configs/mining/status');
    return response.data.data;
  },

  activateMining: async (): Promise<{ success: boolean; message: string }> => {
    const response = await apiClient.post('/configs/mining/activate');
    return response.data.data;
  },

  deactivateMining: async (): Promise<{ success: boolean; message: string }> => {
    const response = await apiClient.post('/configs/mining/deactivate');
    return response.data.data;
  },

  getP2pTransferFee: async (): Promise<{ fee: string; minTransferAmount: string }> => {
    const response = await apiClient.get('/configs/p2p-transfer-fee');
    return response.data.data;
  },

  setP2pTransferFee: async (fee: string, minTransferAmount: string): Promise<void> => {
    await apiClient.post('/configs/p2p-transfer-fee', { fee, minTransferAmount });
  },

  // 获取已配置的池账户列表
  getPoolAccounts: async (): Promise<PoolAccountInfo[]> => {
    const response = await apiClient.get('/admin/pool-accounts');
    return response.data.data;
  },

  // 获取池账户余额（通过 mining-admin-service 代理）
  getPoolAccountBalance: async (walletName: string): Promise<PoolAccountBalance> => {
    const response = await apiClient.get(`/admin/pool-accounts/${walletName}/balance`);
    return response.data.data;
  },

  // 区块链提现（从池账户，通过 mining-admin-service 代理）
  poolAccountBlockchainWithdraw: async (walletName: string, toAddress: string, amount: string): Promise<{
    success: boolean;
    message: string;
    txHash?: string;
    blockNumber?: number;
    newBalance?: string;
    error?: string;
  }> => {
    const response = await apiClient.post(`/admin/pool-accounts/${walletName}/blockchain-withdraw`, { toAddress, amount });
    return response.data.data;
  },

  // 中心化充值（管理员手动调整余额）
  poolAccountCentralizedDeposit: async (walletName: string, amount: string): Promise<{
    success: boolean;
    message: string;
  }> => {
    const response = await apiClient.post(`/admin/pool-accounts/${walletName}/centralized-deposit`, { amount });
    return response.data.data;
  },
};
