import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';

export interface SwapResult {
  success: boolean;
  txHash?: string;
  receivedAmount?: number;
  swapRate?: number;
  error?: string;
}

export interface FundAllocationItem {
  // 目标类型: USER 或 SYSTEM
  targetType: 'USER' | 'SYSTEM';
  // 目标ID: accountSequence (如 D2512120001 或 S0000000001)
  targetId: string;
  // 分配类型 (如 COST_FEE, SHARE_RIGHT 等)
  allocationType: string;
  // 金额 (USDT)
  amount: number;
  // 算力百分比（可选）
  hashpowerPercent?: number;
  // 元数据
  metadata?: Record<string, unknown>;
}

export interface AllocateFundsRequest {
  orderId: string;
  allocations: FundAllocationItem[];
}

export interface AllocateFundsResult {
  success: boolean;
  error?: string;
}

@Injectable()
export class WalletServiceClient {
  private readonly logger = new Logger(WalletServiceClient.name);
  private readonly baseUrl: string;

  constructor(private readonly configService: ConfigService) {
    this.baseUrl = this.configService.get<string>('WALLET_SERVICE_URL', 'http://localhost:3002');
  }

  async executeSwap(params: {
    userId: bigint;
    usdtAmount: number;
    targetCurrency: string; // BNB/OG/USDT/DST
  }): Promise<SwapResult> {
    try {
      const response = await fetch(`${this.baseUrl}/wallet/swap`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          userId: params.userId.toString(),
          usdtAmount: params.usdtAmount,
          targetCurrency: params.targetCurrency,
        }),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        return {
          success: false,
          error: errorData.message || `Swap failed with status ${response.status}`,
        };
      }

      const data = await response.json();
      return {
        success: true,
        txHash: data.txHash,
        receivedAmount: data.receivedAmount,
        swapRate: data.swapRate,
      };
    } catch (error) {
      this.logger.error(`Error executing swap:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  async getSwapRate(fromCurrency: string, toCurrency: string): Promise<number | null> {
    try {
      const response = await fetch(
        `${this.baseUrl}/wallet/swap-rate?from=${fromCurrency}&to=${toCurrency}`,
      );

      if (!response.ok) {
        return null;
      }

      const data = await response.json();
      return data.rate;
    } catch (error) {
      this.logger.error(`Error getting swap rate:`, error);
      return null;
    }
  }

  /**
   * 确认认种扣款
   * 将冻结的资金正式扣除，资金进入"待分配"状态
   * 在合同签署结果确定后调用（contract.signed 或 contract.expired）
   */
  async confirmPlantingDeduction(params: {
    userId: string;
    accountSequence?: string;
    orderId: string;
  }): Promise<{ success: boolean; error?: string }> {
    try {
      this.logger.log(`Confirming planting deduction for order ${params.orderId}`);

      const response = await fetch(`${this.baseUrl}/api/v1/wallets/confirm-planting-deduction`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        this.logger.error(`Failed to confirm deduction for order ${params.orderId}:`, errorData);
        return {
          success: false,
          error: errorData.message || `Confirm deduction failed with status ${response.status}`,
        };
      }

      // wallet-service 使用全局 TransformInterceptor，响应格式为:
      // { success: true, data: { success: boolean, ... }, timestamp: "..." }
      const response_data = await response.json();
      const data = response_data.data || response_data;

      if (data.success !== true) {
        this.logger.error(`Confirm deduction failed for order ${params.orderId}: ${data.error || 'Unknown error'}`);
        return {
          success: false,
          error: data.error || 'Confirm deduction failed',
        };
      }

      this.logger.log(`Successfully confirmed deduction for order ${params.orderId}`);
      return { success: true };
    } catch (error) {
      this.logger.error(`Error confirming deduction for order ${params.orderId}:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * 结算到余额 (可结算USDT → 钱包USDT余额，无币种兑换)
   * 将可结算收益直接转入钱包 USDT 余额
   */
  async settleToBalance(params: {
    accountSequence: string;
    usdtAmount: number;
    rewardEntryIds: string[];
    breakdown?: Record<string, number>;
    memo?: string;
  }): Promise<{
    success: boolean;
    settlementId?: string;
    settledAmount?: number;
    balanceAfter?: number;
    error?: string;
  }> {
    try {
      this.logger.log(`Settling ${params.usdtAmount} USDT to balance for ${params.accountSequence}`);

      const response = await fetch(`${this.baseUrl}/api/v1/wallets/settle-to-balance`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(params),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        this.logger.error(`Failed to settle to balance for ${params.accountSequence}:`, errorData);
        return {
          success: false,
          error: errorData.message || `Settlement failed with status ${response.status}`,
        };
      }

      const response_data = await response.json();
      // wallet-service 使用全局 TransformInterceptor，响应格式为:
      // { success: true, data: { success: boolean, ... }, timestamp: "..." }
      const data = response_data.data || response_data;

      if (data.success !== true) {
        this.logger.error(`Settlement failed for ${params.accountSequence}: ${data.error || 'Unknown error'}`);
        return {
          success: false,
          error: data.error || 'Settlement failed',
        };
      }

      this.logger.log(`Successfully settled to balance for ${params.accountSequence}`);
      return {
        success: true,
        settlementId: data.settlementId,
        settledAmount: data.settledAmount,
        balanceAfter: data.balanceAfter,
      };
    } catch (error) {
      this.logger.error(`Error settling to balance for ${params.accountSequence}:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }

  /**
   * 执行资金分配
   * 将认种订单的资金分配到各个目标账户
   */
  async allocateFunds(request: AllocateFundsRequest): Promise<AllocateFundsResult> {
    try {
      this.logger.log(`Allocating funds for order ${request.orderId}, ${request.allocations.length} targets`);

      const response = await fetch(`${this.baseUrl}/api/v1/wallets/allocate-funds`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(request),
      });

      if (!response.ok) {
        const errorData = await response.json().catch(() => ({}));
        this.logger.error(`Failed to allocate funds for order ${request.orderId}:`, errorData);
        return {
          success: false,
          error: errorData.message || `Allocation failed with status ${response.status}`,
        };
      }

      // wallet-service 使用全局 TransformInterceptor，响应格式为:
      // { success: true, data: { success: boolean, ... }, timestamp: "..." }
      const response_data = await response.json();
      const data = response_data.data || response_data;

      if (data.success !== true) {
        this.logger.error(`Allocate funds failed for order ${request.orderId}: ${data.error || 'Unknown error'}`);
        return {
          success: false,
          error: data.error || 'Allocate funds failed',
        };
      }

      this.logger.log(`Successfully allocated funds for order ${request.orderId}`);
      return { success: true };
    } catch (error) {
      this.logger.error(`Error allocating funds for order ${request.orderId}:`, error);
      return {
        success: false,
        error: error instanceof Error ? error.message : 'Unknown error',
      };
    }
  }
}
