import { fromZonedTime } from "date-fns-tz";
import { fetchWithTimeout, resolveTimeoutMs } from "@open-mercato/shared/lib/http/fetchWithTimeout";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("currencies").child({ component: "raiffeisen" });
const DEFAULT_RATE_FETCH_TIMEOUT_MS = 15e3;
function resolveRateFetchTimeoutMs() {
  const raw = process.env.CURRENCY_RATE_FETCH_TIMEOUT_MS;
  const parsed = raw ? Number.parseInt(raw, 10) : void 0;
  return resolveTimeoutMs(parsed, DEFAULT_RATE_FETCH_TIMEOUT_MS);
}
class RaiffeisenPolandProvider {
  constructor() {
    this.name = "Raiffeisen Bank Polska";
    this.source = "Raiffeisen Bank Polska";
    this.providerBaseCurrency = "PLN";
    this.baseUrl = "https://www.rbinternational.com.pl/rest/rates/";
  }
  isAvailable() {
    return true;
  }
  async fetchRates(date, scope, availableCurrencies) {
    if (!availableCurrencies.has(this.providerBaseCurrency)) {
      logger.debug("Skipping: PLN not found in available currencies");
      return [];
    }
    const dateStr = this.formatDate(date);
    const url = `${this.baseUrl}?type=kursywalut&range=all&date=${dateStr}`;
    try {
      const response = await fetchWithTimeout(url, { timeoutMs: resolveRateFetchTimeoutMs() });
      if (!response.ok) {
        if (response.status === 404) {
          logger.debug("No data available", { date: dateStr });
          return [];
        }
        throw new Error(
          `Raiffeisen API error: ${response.status} ${response.statusText}`
        );
      }
      const data = await response.json();
      if (!data.rates || Object.keys(data.rates).length === 0) {
        return [];
      }
      const times = Object.keys(data.rates).sort((a, b) => a < b ? -1 : a > b ? 1 : 0);
      const firstTime = times[0];
      const rates = data.rates[firstTime];
      const results = [];
      const firstRate = rates[0];
      if (!firstRate) {
        logger.debug("No rates available in time slot", { timeSlot: firstTime });
        return [];
      }
      const rateDate = fromZonedTime(
        `${data.date} ${firstRate.time}`,
        "Europe/Warsaw"
      );
      for (const rateData of rates) {
        const sellRate = parseFloat(rateData.sell);
        results.push({
          fromCurrencyCode: this.providerBaseCurrency,
          toCurrencyCode: rateData.code,
          rate: (1 / sellRate).toString(),
          source: this.source,
          date: rateDate,
          type: "sell"
          // Bank sells foreign currency (from their perspective)
        });
        results.push({
          fromCurrencyCode: rateData.code,
          toCurrencyCode: this.providerBaseCurrency,
          rate: rateData.buy,
          source: this.source,
          date: rateDate,
          type: "buy"
          // Bank buys foreign currency (from their perspective)
        });
      }
      logger.info("Fetched rates", { count: results.length, date: dateStr, time: firstRate.time, rateDate: rateDate.toISOString() });
      return results;
    } catch (err) {
      logger.error("Fetch error", { date: dateStr, err });
      throw new Error(`Failed to fetch Raiffeisen rates: ${err.message}`);
    }
  }
  formatDate(date) {
    return date.toISOString().split("T")[0];
  }
}
export {
  RaiffeisenPolandProvider
};
//# sourceMappingURL=raiffeisen.js.map
