Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
const require_chunk = require("./chunk-DakpK96I.cjs");
const require_session_store = require("./session-store-yfwnj0OC.cjs");
const require_atomic_write = require("./atomic-write-BYmF-ThH.cjs");
let commander = require("commander");
let path = require("path");
path = require_chunk.__toESM(path, 1);
let fs = require("fs");
fs = require_chunk.__toESM(fs, 1);
let slug = require("slug");
slug = require_chunk.__toESM(slug, 1);
let gray_matter = require("gray-matter");
gray_matter = require_chunk.__toESM(gray_matter, 1);
//#region src/commands/create.ts
async function createCustomer(opts) {
	const id = (0, slug.default)(opts.name, { lower: true });
	const dataDir = opts.dataDir ?? process.env["DXCRM_DATA_DIR"] ?? process.cwd();
	await require_session_store.ensureCustomerDir(dataDir, id);
	const dir = path.default.join(dataDir, "customers", id);
	const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
	await require_session_store.writeMainFacts(dataDir, id, {
		name: opts.name,
		domain: opts.domain,
		email: opts.email,
		relationship_stage: "prospect",
		tags: [],
		currency: "EUR",
		created: today,
		updated: today
	});
	const interactionsPath = path.default.join(dir, "interactions.md");
	if (!fs.default.existsSync(interactionsPath)) require_atomic_write.writeFileAtomic(interactionsPath, `# Interactions — ${opts.name}\n\n`);
	const pipelinePath = path.default.join(dir, "pipeline.md");
	if (!fs.default.existsSync(pipelinePath)) require_atomic_write.writeFileAtomic(pipelinePath, `# Pipeline — ${opts.name}\n\n| Deal | Stage | Value | Currency | Probability | Close Date | Updated | Notes |\n|---|---|---|---|---|---|---|---|\n`);
	const sourcesPath = path.default.join(dir, "sources.json");
	if (!fs.default.existsSync(sourcesPath)) require_session_store.writeJsonFile(sourcesPath, {
		gmail: {
			type: "gmail",
			query: opts.domain ? `from:${opts.domain} OR to:${opts.domain}` : opts.email ? `from:${opts.email} OR to:${opts.email}` : "",
			enabled: true
		},
		version: 1,
		created: (/* @__PURE__ */ new Date()).toISOString()
	});
	return {
		id,
		dir
	};
}
new commander.Command("create").description("Create a new customer").argument("<name>", "Customer name").option("--domain <domain>", "Primary domain (for Gmail sync)").option("--email <email>", "Primary contact email").action(async (name, opts) => {
	try {
		const { id, dir } = await createCustomer({
			name,
			...opts
		});
		console.log(require_session_store.success(`✓ Created customer: ${require_session_store.bold(id)}`));
		console.log(`  Dir: ${dir}`);
		console.log(`  Files: main_facts.md, interactions.md, pipeline.md, sources.json`);
	} catch (err) {
		console.error(require_session_store.error(`✗ ${err.message}`));
		process.exit(1);
	}
});
//#endregion
//#region src/commands/audit.ts
const SEP = "─".repeat(70);
async function runAudit(opts, dataDir) {
	const dir = dataDir ?? process.cwd();
	const limit = opts.limit ?? 20;
	const entries = require_session_store.filterAuditLog(require_session_store.readAuditLog(dir), {
		...opts.slug !== void 0 ? { slug: opts.slug } : {},
		...opts.actor !== void 0 ? { actor: opts.actor } : {},
		limit
	});
	console.log(SEP);
	console.log(" DatasynxOpenCRM — Audit Trail");
	if (opts.slug) console.log(` Customer: ${opts.slug}`);
	if (opts.actor) console.log(` Actor:    ${opts.actor}`);
	console.log(SEP);
	if (entries.length === 0) {
		console.log(" No audit entries found.");
		console.log(SEP);
		return;
	}
	for (const entry of entries) console.log(` ${entry.timestamp}  ${entry.actor.padEnd(12)}  ${entry.tool.padEnd(20)}  ${entry.slug.padEnd(20)}  ${entry.summary}`);
	console.log(SEP);
	console.log(` ${entries.length} entr${entries.length === 1 ? "y" : "ies"} shown`);
	console.log(SEP);
}
new commander.Command("audit").description("Show CRM audit trail — who changed what and when").option("--slug <slug>", "Filter by customer slug").option("--actor <actor>", "Filter by actor").option("--limit <n>", "Number of entries to show (default: 20)", parseInt).option("--tail", "Show all new entries (simplified: shows current entries)").action((opts) => runAudit(opts, process.env["DXCRM_DATA_DIR"]));
//#endregion
//#region src/commands/validate.ts
const RECOVERABLE_DEFAULTS = {
	tags: [],
	currency: "EUR"
};
function applyFix(factsPath, content, data) {
	const fixed = [];
	const patched = { ...data };
	for (const [field, defaultValue] of Object.entries(RECOVERABLE_DEFAULTS)) if (patched[field] === void 0 || patched[field] === null) {
		patched[field] = defaultValue;
		fixed.push(`${field} → ${JSON.stringify(defaultValue)}`);
	}
	if (patched["updated"] === void 0 && patched["created"]) {
		patched["updated"] = patched["created"];
		fixed.push(`updated → ${String(patched["created"])}`);
	}
	if (fixed.length === 0) return null;
	const parsed = (0, gray_matter.default)(content);
	const newContent = gray_matter.default.stringify(parsed.content, patched);
	fs.default.writeFileSync(factsPath, newContent);
	return {
		fixed,
		content: newContent
	};
}
async function runValidate(opts, dataDir) {
	const customersDir = path.default.join(dataDir, "customers");
	if (!fs.default.existsSync(customersDir)) {
		console.log(require_session_store.warning("⚠ No customers directory found."));
		return;
	}
	const slugs = require_session_store.listCustomerSlugs(dataDir);
	let errorCount = 0;
	let fixedCount = 0;
	for (const slug of slugs) {
		const factsPath = path.default.join(customersDir, slug, "main_facts.md");
		const interactionsPath = path.default.join(customersDir, slug, "interactions.md");
		if (!fs.default.existsSync(factsPath)) {
			console.log(require_session_store.error(`✗ ${slug}: missing main_facts.md`));
			errorCount++;
			continue;
		}
		try {
			let content = fs.default.readFileSync(factsPath, "utf-8");
			let parsed = (0, gray_matter.default)(content);
			if (opts.fix) {
				const result = applyFix(factsPath, content, parsed.data);
				if (result) {
					content = result.content;
					parsed = (0, gray_matter.default)(content);
					fixedCount++;
					console.log(require_session_store.info(`⚙ ${slug}: fixed ${result.fixed.join(", ")}`));
				}
			}
			require_session_store.MainFactsSchema.parse(parsed.data);
			if (!fs.default.existsSync(interactionsPath)) console.log(require_session_store.warning(`⚠ ${slug}: missing interactions.md`));
			else console.log(require_session_store.success(`✓ ${slug}`));
		} catch (err) {
			console.log(require_session_store.error(`✗ ${slug}: ${err.message}`));
			errorCount++;
		}
	}
	if (opts.fix && fixedCount > 0) console.log(require_session_store.info(`\n⚙ Fixed ${fixedCount} customer(s).`));
	if (errorCount > 0) {
		console.error(require_session_store.error(`\n${errorCount} error(s) found.`));
		process.exit(1);
	} else console.log(require_session_store.success("\n✓ All customers valid."));
}
new commander.Command("validate").description("Validate all customer data against schemas").option("--fix", "Auto-fix recoverable issues").action(async (opts) => {
	await runValidate(opts, process.env["DXCRM_DATA_DIR"] ?? process.cwd());
});
//#endregion
//#region src/version.ts
const VERSION = "0.1.0";
//#endregion
exports.VERSION = VERSION;
exports.canSeeCustomer = require_session_store.canSeeCustomer;
exports.clearSession = require_session_store.clearSession;
exports.createCustomer = createCustomer;
exports.customerExists = require_session_store.customerExists;
exports.filterAuditLog = require_session_store.filterAuditLog;
exports.getRbacConfig = require_session_store.getRbacConfig;
exports.getRole = require_session_store.getRole;
exports.getSession = require_session_store.getSession;
exports.readAuditLog = require_session_store.readAuditLog;
exports.readMainFacts = require_session_store.readMainFacts;
exports.runAudit = runAudit;
exports.runBackup = require_session_store.runBackup;
exports.runValidate = runValidate;
exports.setSession = require_session_store.setSession;

//# sourceMappingURL=index.cjs.map