import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { RateFetchingService } from "./services/rateFetchingService.js";
import { NBPProvider } from "./services/providers/nbp.js";
import { RaiffeisenPolandProvider } from "./services/providers/raiffeisen.js";
import { CurrencyFetchConfig } from "./data/entities.js";
import { seedExampleCurrencies } from "./lib/seeds.js";
function parseArgs(args) {
  const result = {};
  for (let i = 0; i < args.length; i++) {
    const arg = args[i];
    if (arg.startsWith("--")) {
      const key = arg.slice(2);
      if (arg.includes("=")) {
        const [k, v] = arg.slice(2).split("=");
        result[k] = v;
      } else {
        const nextArg = args[i + 1];
        if (nextArg && !nextArg.startsWith("--")) {
          result[key] = nextArg;
          i++;
        } else {
          result[key] = true;
        }
      }
    }
  }
  return result;
}
const fetchRatesCommand = {
  command: "fetch-rates",
  async run(rest) {
    const args = parseArgs(rest);
    const tenantId = String(args.tenantId ?? args.tenant ?? "");
    const organizationId = String(args.organizationId ?? args.org ?? "");
    if (!tenantId || !organizationId) {
      console.error(
        "Usage: mercato currencies fetch-rates --tenant <id> --org <id> [options]"
      );
      console.error("Options:");
      console.error("  --date YYYY-MM-DD       Fetch for specific date (default: today)");
      console.error("  --from YYYY-MM-DD       Start date for range");
      console.error("  --to YYYY-MM-DD         End date for range");
      console.error("  --provider NAME         Specific provider (default: all enabled)");
      return;
    }
    const container = await createRequestContainer();
    try {
      const em = container.resolve("em");
      const fetchService = new RateFetchingService(em);
      fetchService.registerProvider(new NBPProvider());
      fetchService.registerProvider(new RaiffeisenPolandProvider());
      const dateStr = String(args.date || "");
      const fromStr = String(args.from || "");
      const toStr = String(args.to || "");
      const providerArg = args.provider ? String(args.provider) : null;
      let dates = [];
      if (fromStr && toStr) {
        const from = new Date(fromStr);
        const to = new Date(toStr);
        const current = new Date(from);
        while (current <= to) {
          dates.push(new Date(current));
          current.setDate(current.getDate() + 1);
        }
        console.log(
          `\u{1F4C5} Fetching rates for date range: ${fromStr} to ${toStr} (${dates.length} days)`
        );
      } else if (dateStr) {
        dates = [new Date(dateStr)];
        console.log(`\u{1F4C5} Fetching rates for: ${dateStr}`);
      } else {
        dates = [/* @__PURE__ */ new Date()];
        console.log(`\u{1F4C5} Fetching rates for today`);
      }
      const providers = providerArg ? providerArg.split(",").map((p) => p.trim()) : void 0;
      let totalFetched = 0;
      const allErrors = [];
      for (const date of dates) {
        const dateStr2 = date.toISOString().split("T")[0];
        console.log(`
\u{1F504} Fetching for ${dateStr2}...`);
        const result = await fetchService.fetchRatesForDate(
          date,
          { tenantId, organizationId },
          { providers }
        );
        totalFetched += result.totalFetched;
        console.log(`  \u2705 Fetched ${result.totalFetched} rates`);
        for (const [provider, data] of Object.entries(result.byProvider)) {
          console.log(`    ${provider}: ${data.count} rates`);
          if (data.errors?.length) {
            data.errors.forEach((err) => console.log(`      \u26A0\uFE0F  ${err}`));
          }
        }
        if (result.errors.length > 0) {
          result.errors.forEach((err) => console.log(`  \u274C ${err}`));
          allErrors.push(...result.errors);
        }
      }
      console.log(`
\u2728 Complete! Total rates fetched: ${totalFetched}`);
      if (allErrors.length > 0) {
        console.log(`\u26A0\uFE0F  Encountered ${allErrors.length} error(s)`);
      }
    } catch (err) {
      console.error("\u274C Error:", err.message);
      process.exit(1);
    } finally {
      await container.dispose?.();
    }
  }
};
const listProvidersCommand = {
  command: "list-providers",
  async run(rest) {
    const args = parseArgs(rest);
    const tenantId = String(args.tenantId ?? args.tenant ?? "");
    const organizationId = String(args.organizationId ?? args.org ?? "");
    console.log("\u{1F4CB} Available Currency Rate Providers:\n");
    console.log("  \u2022 NBP (National Bank of Poland)");
    console.log("    - ~13 currencies with bid/ask rates");
    console.log("    - Table C: Buy/Sell rates");
    console.log("");
    console.log("  \u2022 Raiffeisen Bank Polska");
    console.log("    - 4 major currencies (EUR, USD, CHF, GBP)");
    console.log("    - Intraday rates with buy/sell spreads");
    if (tenantId && organizationId) {
      const container = await createRequestContainer();
      try {
        const em = container.resolve("em");
        const configs = await em.find(CurrencyFetchConfig, {
          tenantId,
          organizationId
        });
        if (configs.length > 0) {
          console.log("\n\u{1F4CA} Configuration Status:");
          for (const config of configs) {
            const status = config.isEnabled ? "\u2705 Enabled" : "\u2B55 Disabled";
            const lastSync = config.lastSyncAt ? new Date(config.lastSyncAt).toISOString() : "Never";
            console.log(`
  ${config.provider}: ${status}`);
            console.log(`    Last Sync: ${lastSync}`);
            if (config.lastSyncCount !== null) {
              console.log(`    Last Count: ${config.lastSyncCount} rates`);
            }
            if (config.syncTime) {
              console.log(`    Scheduled: Daily at ${config.syncTime}`);
            }
          }
        }
      } finally {
        await container.dispose?.();
      }
    }
  }
};
const seed = {
  command: "seed",
  async run(rest) {
    const args = parseArgs(rest);
    const tenantId = String(args.tenantId ?? args.tenant ?? "");
    const organizationId = String(args.organizationId ?? args.orgId ?? args.org ?? "");
    if (!tenantId || !organizationId) {
      console.error("Usage: mercato currencies seed --tenant <tenantId> --org <organizationId>");
      return;
    }
    const container = await createRequestContainer();
    const em = container.resolve("em");
    const seeded = await em.transactional(async (tem) => {
      return seedExampleCurrencies(tem, { tenantId, organizationId });
    });
    console.log(seeded ? "Currencies seeded for organization" : "Currencies already present; skipping", organizationId);
  }
};
var cli_default = [seed, fetchRatesCommand, listProvidersCommand];
export {
  cli_default as default
};
//# sourceMappingURL=cli.js.map
