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: "nbp" });
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 NBPProvider {
  constructor() {
    this.name = "NBP (National Bank of Poland)";
    this.source = "NBP";
    this.providerBaseCurrency = "PLN";
    this.baseUrl = "https://api.nbp.pl/api";
  }
  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}/exchangerates/tables/c/${dateStr}/?format=json`;
    try {
      const response = await fetchWithTimeout(url, { timeoutMs: resolveRateFetchTimeoutMs() });
      if (response.status === 404) {
        logger.debug("No data available", { date: dateStr });
        return [];
      }
      if (!response.ok) {
        throw new Error(`NBP API error: ${response.status} ${response.statusText}`);
      }
      const data = await response.json();
      if (!data || data.length === 0) {
        return [];
      }
      const table = data[0];
      const results = [];
      const effectiveDate = fromZonedTime(
        `${table.effectiveDate} 00:00:00`,
        "Europe/Warsaw"
      );
      for (const rate of table.rates) {
        results.push({
          fromCurrencyCode: this.providerBaseCurrency,
          toCurrencyCode: rate.code,
          rate: (1 / rate.ask).toString(),
          source: this.source,
          date: effectiveDate,
          type: "sell"
          // Bank sells foreign currency (from their perspective)
        });
        results.push({
          fromCurrencyCode: rate.code,
          toCurrencyCode: this.providerBaseCurrency,
          rate: rate.bid.toString(),
          source: this.source,
          date: effectiveDate,
          type: "buy"
          // Bank buys foreign currency (from their perspective)
        });
      }
      logger.info("Fetched rates", { count: results.length, date: dateStr });
      return results;
    } catch (err) {
      logger.error("Fetch error", { date: dateStr, err });
      throw new Error(`Failed to fetch NBP rates: ${err.message}`);
    }
  }
  formatDate(date) {
    return date.toISOString().split("T")[0];
  }
}
export {
  NBPProvider
};
//# sourceMappingURL=nbp.js.map
