import { logger } from '../../utils/logger';

interface ExchangeRateResult {
  rate: number;
  timestamp: number;
}

export class ExchangeRateService {
  static async getExchangeRate(fromCurrency: string, toCurrency: string): Promise<ExchangeRateResult | null> {
    try {
      // 模拟汇率数据
      const mockRates: Record<string, number> = {
        'CNY/USD': 0.14,
        'USD/CNY': 7.14,
        'CNY/EUR': 0.13,
        'EUR/CNY': 7.69,
        'USD/EUR': 0.93,
        'EUR/USD': 1.08
      };
      
      const key = `${fromCurrency}/${toCurrency}`;
      if (mockRates[key]) {
        return {
          rate: mockRates[key],
          timestamp: Date.now()
        };
      }
      
      // 如果没有直接的汇率，尝试通过USD中转
      if (fromCurrency !== 'USD' && toCurrency !== 'USD') {
        const fromToUSD = await this.getExchangeRate(fromCurrency, 'USD');
        const usdToTo = await this.getExchangeRate('USD', toCurrency);
        if (fromToUSD && usdToTo) {
          return {
            rate: fromToUSD.rate * usdToTo.rate,
            timestamp: Date.now()
          };
        }
      }
      
      return null;
    } catch (error) {
      logger.error('Error getting exchange rate:', error);
      return null;
    }
  }

  static async updateExchangeRates(): Promise<number> {
    // 模拟实现：更新汇率
    return 5; // 模拟更新了5条汇率
  }

  static async getExchangeRateHistory(fromCurrency: string, toCurrency: string, days: number): Promise<any[]> {
    // 模拟实现：返回汇率历史
    const history: any[] = [];
    const baseRate = 7.2;
    
    for (let i = 0; i < days; i++) {
      const date = new Date();
      date.setDate(date.getDate() - i);
      history.push({
        date: date.toISOString(),
        rate: baseRate + (Math.random() * 0.2 - 0.1),
        fromCurrency: fromCurrency.toUpperCase(),
        toCurrency: toCurrency.toUpperCase()
      });
    }
    
    return history;
  }

  static async getAllExchangeRates(): Promise<any[]> {
    // 模拟实现：返回所有汇率
    return [
      { from: 'USD', to: 'CNY', rate: 7.2 },
      { from: 'CNY', to: 'USD', rate: 0.1389 },
      { from: 'EUR', to: 'USD', rate: 1.1 },
      { from: 'USD', to: 'EUR', rate: 0.9091 },
      { from: 'GBP', to: 'USD', rate: 1.25 },
      { from: 'USD', to: 'GBP', rate: 0.8 }
    ];
  }
}

export default ExchangeRateService;