import { exchangeApi, ExchangeRateResponse } from './api/exchange';

class ExchangeDataSource {
  private rates: Record<string, number> = {};
  private lastUpdate: Date | null = null;
  private updateInterval = 60 * 60 * 1000; // 1小时更新一次

  /**
   * 获取最新汇率
   * @param base 基准货币，默认为EUR
   * @returns 汇率数据
   */
  async getLatestRates(base: string = 'EUR'): Promise<ExchangeRateResponse> {
    return exchangeApi.getLatestRates(base);
  }

  /**
   * 货币转换
   * @param from 源货币
   * @param to 目标货币
   * @param amount 金额
   * @returns 转换后的金额
   */
  async convertCurrency(from: string, to: string, amount: number): Promise<number> {
    return exchangeApi.convertCurrency(from, to, amount);
  }

  /**
   * 批量货币转换
   * @param from 源货币
   * @param toCurrencies 目标货币列表
   * @param amount 金额
   * @returns 转换后的金额映射
   */
  async batchConvertCurrency(from: string, toCurrencies: string[], amount: number): Promise<Record<string, number>> {
    try {
      const rates = await this.getLatestRates(from);
      const result: Record<string, number> = {};
      
      toCurrencies.forEach(currency => {
        if (rates.rates[currency]) {
          result[currency] = amount * rates.rates[currency];
        }
      });
      
      return result;
    } catch (error) {
      console.error('批量货币转换失败:', error);
      throw error;
    }
  }

  /**
   * 获取汇率（带缓存）
   * @param from 源货币
   * @param to 目标货币
   * @returns 汇率
   */
  async getExchangeRate(from: string, to: string): Promise<number> {
    const cacheKey = `${from}_${to}`;
    
    // 检查缓存是否有效
    if (this.rates[cacheKey] && this.lastUpdate) {
      const timeDiff = Date.now() - this.lastUpdate.getTime();
      if (timeDiff < this.updateInterval) {
        return this.rates[cacheKey];
      }
    }

    // 获取新汇率
    try {
      const result = await exchangeApi.convertCurrency(from, to, 1);
      this.rates[cacheKey] = result;
      this.lastUpdate = new Date();
      return result;
    } catch (error) {
      console.error('获取汇率失败:', error);
      throw error;
    }
  }

  /**
   * 刷新汇率缓存
   */
  async refreshRates(): Promise<void> {
    try {
      const rates = await this.getLatestRates();
      this.rates = rates.rates;
      this.lastUpdate = new Date();
    } catch (error) {
      console.error('刷新汇率缓存失败:', error);
      throw error;
    }
  }

  /**
   * 获取支持的货币列表
   * @returns 货币代码列表
   */
  async getSupportedCurrencies(): Promise<string[]> {
    try {
      const rates = await this.getLatestRates();
      return Object.keys(rates.rates);
    } catch (error) {
      console.error('获取支持的货币列表失败:', error);
      throw error;
    }
  }
}

export const exchangeDataSource = new ExchangeDataSource();