import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PlatformConfig } from '@/entities/platform-config.entity';

@Injectable()
export class ConfigService {
  constructor(
    @InjectRepository(PlatformConfig)
    private configRepo: Repository<PlatformConfig>,
  ) {}

  async getConfig(key: string): Promise<string | null> {
    const config = await this.configRepo.findOne({ where: { configKey: key } });
    return config?.configValue || null;
  }

  async setConfig(key: string, value: string, description?: string): Promise<void> {
    let config = await this.configRepo.findOne({ where: { configKey: key } });
    if (config) {
      config.configValue = value;
      if (description) config.description = description;
    } else {
      config = this.configRepo.create({ configKey: key, configValue: value, description });
    }
    await this.configRepo.save(config);
  }

  async getServiceFeeRate(): Promise<number> {
    const value = await this.getConfig('service_fee_rate');
    const rate = parseFloat(value || '0.05');
    return isNaN(rate) ? 0.05 : rate;
  }

  async getCommissionRate(): Promise<number> {
    const value = await this.getConfig('commission_rate');
    const rate = parseFloat(value || '0.10');
    return isNaN(rate) ? 0.10 : rate;
  }

  async getServiceFeeConfig(): Promise<{ rate: number; description: string }> {
    const value = await this.getConfig('service_fee_rate');
    const config = await this.configRepo.findOne({ where: { configKey: 'service_fee_rate' } });
    const rate = parseFloat(value || '0.05');
    return {
      rate: isNaN(rate) ? 0.05 : rate,
      description: config?.description || '软件服务费比例',
    };
  }

  async updateServiceFeeRate(rate: number): Promise<void> {
    if (rate < 0 || rate > 1) {
      throw new Error('服务费比例必须在0-1之间');
    }
    await this.setConfig('service_fee_rate', rate.toString(), '软件服务费比例');
  }

  async getAllConfigs() {
    return this.configRepo.find({ order: { createdAt: 'DESC' } });
  }

  async deleteConfig(key: string): Promise<void> {
    await this.configRepo.delete({ configKey: key });
  }
}
