import { Injectable } from '@nestjs/common';
import { PrismaService } from '@/infrastructure/persistence/prisma/prisma.service';
import { FeeType, WithdrawalFeeConfigResponseDTO } from '@/api/dto/response';

/**
 * 默认手续费配置 (当数据库无配置时使用)
 */
const DEFAULT_FEE_CONFIG: WithdrawalFeeConfigResponseDTO = {
  feeType: FeeType.FIXED,
  feeValue: 2, // 固定 2 绿积分
  minFee: 0,
  maxFee: 0,
  memo: '默认配置：固定 2 绿积分/笔',
};

@Injectable()
export class FeeConfigRepositoryImpl {
  constructor(private readonly prisma: PrismaService) {}

  /**
   * 获取当前生效的手续费配置
   * 如果没有配置，返回默认配置 (固定 2 绿积分/笔)
   */
  async getActiveConfig(): Promise<WithdrawalFeeConfigResponseDTO> {
    const config = await this.prisma.withdrawalFeeConfig.findFirst({
      where: { isActive: true },
      orderBy: { createdAt: 'desc' },
    });

    if (!config) {
      return DEFAULT_FEE_CONFIG;
    }

    return {
      feeType: config.feeType as FeeType,
      feeValue: Number(config.feeValue),
      minFee: Number(config.minFee),
      maxFee: Number(config.maxFee),
      memo: config.memo ?? undefined,
    };
  }

  /**
   * 计算手续费
   * @param amount 提取金额
   * @returns 手续费金额
   */
  async calculateFee(amount: number): Promise<{
    fee: number;
    feeType: FeeType;
    feeValue: number;
  }> {
    const config = await this.getActiveConfig();
    let fee: number;

    if (config.feeType === FeeType.FIXED) {
      // 固定金额
      fee = config.feeValue;
    } else {
      // 百分比
      fee = amount * config.feeValue;

      // 应用最小/最大限制
      if (config.minFee > 0 && fee < config.minFee) {
        fee = config.minFee;
      }
      if (config.maxFee > 0 && fee > config.maxFee) {
        fee = config.maxFee;
      }
    }

    return {
      fee,
      feeType: config.feeType,
      feeValue: config.feeValue,
    };
  }
}
