// for exchangerate-api.com/
import { setExchangeRates } from "../slice/currencyExchangeRateSlice";
import { AppDispatch } from "../store";

// const API_KEY = "f1005fd4e3525cacc6da9ff2"; // Replace with your key

export const fetchExchangeRatesIfNeeded = async (
  dispatch: AppDispatch,
  lastFetched: string | null
) => {
  const now = new Date();
  const last = lastFetched ? new Date(lastFetched) : null;

  // If more than 24h or no data, fetch
  if (!last || now.getTime() - last.getTime() > 6 * 60 * 60 * 1000) {
    // const res = await fetch(`https://v6.exchangerate-api.com/v6/${API_KEY}/latest/USD`);
    const res = await fetch(
      `https://admin.reservitt.com/api/currency/exchange`
    );
    const data = await res.json();
    const rates = {
      USD: 1,
      CAD: data?.data?.rate,
    };

    dispatch(setExchangeRates({ rates, fetchedAt: now.toISOString() }));
  }
};