import exchangeRateService from './ExchangeRateService';
import currencyService from './CurrencyService';
import { logger } from '../utils/logger';

export class CurrencyConversionService {
  async convert(amount: number, fromCurrency: string, toCurrency: string): Promise<number> {
    try {
      // 验证金额
      if (amount < 0) {
        throw new Error('Amount cannot be negative');
      }

      // 相同货币直接返回
      if (fromCurrency === toCurrency) {
        logger.info(`[CurrencyConversionService] Same currency conversion: ${fromCurrency} to ${toCurrency}`);
        return amount;
      }

      // 获取汇率
      const rate = await exchangeRateService.getExchangeRate(fromCurrency, toCurrency);
      if (!rate) {
        throw new Error(`Exchange rate not found for ${fromCurrency} to ${toCurrency}`);
      }

      // 计算转换金额
      const convertedAmount = amount * rate.rate;
      logger.info(`[CurrencyConversionService] Converted ${amount} ${fromCurrency} to ${convertedAmount} ${toCurrency} using rate ${rate.rate}`);

      return convertedAmount;
    } catch (error) {
      logger.error('[CurrencyConversionService] Error converting currency:', error);
      throw new Error('Failed to convert currency');
    }
  }

  async convertMultiple(amounts: number[], fromCurrency: string, toCurrency: string): Promise<number[]> {
    try {
      // 获取汇率
      const rate = await exchangeRateService.getExchangeRate(fromCurrency, toCurrency);
      if (!rate) {
        throw new Error(`Exchange rate not found for ${fromCurrency} to ${toCurrency}`);
      }

      // 批量转换
      const convertedAmounts = amounts.map(amount => {
        if (amount < 0) {
          throw new Error('Amount cannot be negative');
        }
        return amount * rate.rate;
      });

      logger.info(`[CurrencyConversionService] Converted ${amounts.length} amounts from ${fromCurrency} to ${toCurrency}`);
      return convertedAmounts;
    } catch (error) {
      logger.error('[CurrencyConversionService] Error converting multiple currencies:', error);
      throw new Error('Failed to convert multiple currencies');
    }
  }

  async convertToDefault(amount: number, fromCurrency: string): Promise<number> {
    try {
      // 获取默认货币
      const defaultCurrency = await currencyService.getDefaultCurrency();
      if (!defaultCurrency) {
        throw new Error('No default currency set');
      }

      // 转换到默认货币
      return await this.convert(amount, fromCurrency, defaultCurrency.code);
    } catch (error) {
      logger.error('[CurrencyConversionService] Error converting to default currency:', error);
      throw new Error('Failed to convert to default currency');
    }
  }

  async convertFromDefault(amount: number, toCurrency: string): Promise<number> {
    try {
      // 获取默认货币
      const defaultCurrency = await currencyService.getDefaultCurrency();
      if (!defaultCurrency) {
        throw new Error('No default currency set');
      }

      // 从默认货币转换
      return await this.convert(amount, defaultCurrency.code, toCurrency);
    } catch (error) {
      logger.error('[CurrencyConversionService] Error converting from default currency:', error);
      throw new Error('Failed to convert from default currency');
    }
  }

  async getConversionRate(fromCurrency: string, toCurrency: string): Promise<number> {
    try {
      // 获取汇率
      const rate = await exchangeRateService.getExchangeRate(fromCurrency, toCurrency);
      if (!rate) {
        throw new Error(`Exchange rate not found for ${fromCurrency} to ${toCurrency}`);
      }

      logger.info(`[CurrencyConversionService] Retrieved conversion rate: ${fromCurrency} to ${toCurrency} = ${rate.rate}`);
      return rate.rate;
    } catch (error) {
      logger.error('[CurrencyConversionService] Error getting conversion rate:', error);
      throw new Error('Failed to get conversion rate');
    }
  }

  async calculateCrossConversion(amount: number, fromCurrency: string, toCurrency: string, viaCurrency: string = 'USD'): Promise<number> {
    try {
      // 计算交叉汇率
      const crossRate = await exchangeRateService.calculateCrossRate(fromCurrency, toCurrency, viaCurrency);
      if (crossRate === null) {
        throw new Error(`Cross rate calculation failed for ${fromCurrency} to ${toCurrency} via ${viaCurrency}`);
      }

      // 计算转换金额
      const convertedAmount = amount * crossRate;
      logger.info(`[CurrencyConversionService] Cross converted ${amount} ${fromCurrency} to ${convertedAmount} ${toCurrency} via ${viaCurrency} using rate ${crossRate}`);

      return convertedAmount;
    } catch (error) {
      logger.error('[CurrencyConversionService] Error calculating cross conversion:', error);
      throw new Error('Failed to calculate cross conversion');
    }
  }

  async convertWithDate(amount: number, fromCurrency: string, toCurrency: string, date: Date): Promise<number> {
    try {
      // 验证金额
      if (amount < 0) {
        throw new Error('Amount cannot be negative');
      }

      // 相同货币直接返回
      if (fromCurrency === toCurrency) {
        return amount;
      }

      // 这里可以添加历史汇率查询逻辑
      // 目前暂时使用当前汇率
      return await this.convert(amount, fromCurrency, toCurrency);
    } catch (error) {
      logger.error('[CurrencyConversionService] Error converting with date:', error);
      throw new Error('Failed to convert with date');
    }
  }
}

export default new CurrencyConversionService();
