import { createRequestContainer } from "@open-mercato/shared/lib/di/container";
import { BusinessRule } from "./data/entities.js";
import {
  invalidateBusinessRuleDiscoveryCache,
  resolveBusinessRuleDiscoveryCache
} from "./lib/rule-engine.js";
import * as fs from "fs";
import * as path from "path";
function parseArgs(args) {
  const result = {};
  for (let i = 0; i < args.length; i += 2) {
    const key = args[i]?.replace(/^-+/, "");
    const value = args[i + 1];
    if (key && value) {
      result[key] = value;
    }
  }
  return result;
}
const seedGuardRules = {
  command: "seed-guard-rules",
  async run(rest) {
    const args = parseArgs(rest);
    const tenantId = String(args.tenantId ?? args.tenant ?? args.t ?? "");
    const organizationId = String(args.organizationId ?? args.orgId ?? args.org ?? args.o ?? "");
    if (!tenantId || !organizationId) {
      console.error("Usage: mercato business_rules seed-guard-rules --tenant <tenantId> --org <organizationId>");
      console.error("   or: mercato business_rules seed-guard-rules -t <tenantId> -o <organizationId>");
      return;
    }
    try {
      const { resolve } = await createRequestContainer();
      const em = resolve("em");
      const cache = resolveBusinessRuleDiscoveryCache(resolve);
      const rulesPath = path.join(__dirname, "../workflows/examples", "guard-rules-example.json");
      const rulesData = JSON.parse(fs.readFileSync(rulesPath, "utf8"));
      console.log("\u{1F9E0} Seeding guard rules...");
      let seededCount = 0;
      let skippedCount = 0;
      for (const ruleData of rulesData) {
        const existing = await em.findOne(BusinessRule, {
          ruleId: ruleData.ruleId,
          tenantId,
          organizationId
        });
        if (existing) {
          console.log(`  \u2298 Guard rule '${ruleData.ruleId}' already exists`);
          skippedCount++;
          continue;
        }
        const rule = em.create(BusinessRule, {
          ...ruleData,
          tenantId,
          organizationId
        });
        await em.persist(rule).flush();
        await invalidateBusinessRuleDiscoveryCache(cache, tenantId, organizationId);
        console.log(`  \u2713 Seeded guard rule: ${rule.ruleName}`);
        seededCount++;
      }
      console.log(`
\u2705 Guard rules seeding complete:`);
      console.log(`  - Seeded: ${seededCount}`);
      console.log(`  - Skipped (existing): ${skippedCount}`);
      console.log(`  - Total: ${rulesData.length}`);
    } catch (error) {
      console.error("Error seeding guard rules:", error);
      throw error;
    }
  }
};
const businessRulesCliCommands = [
  seedGuardRules
];
var cli_default = businessRulesCliCommands;
export {
  cli_default as default
};
//# sourceMappingURL=cli.js.map
