import axios from 'axios';

interface ExchangeRateResponse {
  amount: number;
  base: string;
  date: string;
  rates: Record<string, number>;
}

const exchangeApi = {
  /**
   * 获取最新汇率
   * @param base 基准货币，默认为EUR
   * @returns 汇率数据
   */
  getLatestRates: async (base: string = 'EUR'): Promise<ExchangeRateResponse> => {
    try {
      const response = await axios.get<ExchangeRateResponse>(
        `https://api.frankfurter.app/latest`,
        {
          params: { base }
        }
      );
      return response.data;
    } catch (error) {
      console.error('获取汇率失败:', error);
      throw error;
    }
  },

  /**
   * 货币转换
   * @param from 源货币
   * @param to 目标货币
   * @param amount 金额
   * @returns 转换后的金额
   */
  convertCurrency: async (from: string, to: string, amount: number): Promise<number> => {
    try {
      const rates = await exchangeApi.getLatestRates(from);
      const rate = rates.rates[to];
      if (!rate) {
        throw new Error(`未找到货币 ${to} 的汇率`);
      }
      return amount * rate;
    } catch (error) {
      console.error('货币转换失败:', error);
      throw error;
    }
  }
};

export { exchangeApi };
export type { ExchangeRateResponse };