import { i as listCustomerSlugs, t as assertSafeSlug } from "./customer-dir-CkMMXhb0.js";
import { t as writeFileAtomic } from "./atomic-write-8yjqqLtS.js";
import path from "path";
import fs from "fs";
import { z } from "zod";
//#region src/schemas/ticket.ts
const TicketStatusSchema = z.enum([
	"open",
	"in-progress",
	"waiting",
	"resolved",
	"closed"
]);
const TicketPrioritySchema = z.enum([
	"urgent",
	"high",
	"normal",
	"low"
]);
const TicketSchema = z.object({
	id: z.string().regex(/^T-\d{3,}$/),
	title: z.string().min(1),
	status: TicketStatusSchema,
	priority: TicketPrioritySchema.default("normal"),
	assignee: z.string().optional(),
	created: z.string().regex(/^\d{4}-\d{2}-\d{2}$/),
	slaDue: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
	resolved: z.string().regex(/^\d{4}-\d{2}-\d{2}$/).optional(),
	description: z.string().optional()
});
//#endregion
//#region src/fs/ticket-writer.ts
const TICKET_HEADER = "# Tickets\n\n";
const TABLE_HEADER = `| ID | Title | Status | Priority | Assignee | Created | SLA Due | Resolved |
|----|-------|--------|----------|----------|---------|---------|---------|`;
function ticketsPath(dataDir, slug) {
	assertSafeSlug(slug);
	return path.join(dataDir, "customers", slug, "tickets.md");
}
function escapeMd(s) {
	return (s ?? "").replace(/\|/g, "\\|").replace(/\n/g, " ");
}
function parseTicketsFromMarkdown(content) {
	const tickets = [];
	const lines = content.split("\n");
	let inTable = false;
	for (const line of lines) {
		if (line.startsWith("| ID |") || line.startsWith("|----")) {
			inTable = true;
			continue;
		}
		if (!inTable) continue;
		if (!line.startsWith("|")) {
			inTable = false;
			continue;
		}
		const cols = line.split("|").slice(1, -1).map((c) => c.trim());
		if (cols.length < 8) continue;
		const [id, title, status, priority, assignee, created, slaDue, resolved] = cols;
		if (!id || !title || id === "ID") continue;
		const raw = {
			id,
			title,
			status: status || "open",
			priority: priority || "normal",
			...assignee ? { assignee } : {},
			created: created || (/* @__PURE__ */ new Date()).toISOString().slice(0, 10),
			...slaDue ? { slaDue } : {},
			...resolved ? { resolved } : {}
		};
		const parsed = TicketSchema.safeParse(raw);
		if (parsed.success) tickets.push(parsed.data);
	}
	return tickets;
}
function serializeTickets(tickets) {
	return `${TICKET_HEADER}${TABLE_HEADER}\n${tickets.map((t) => `| ${t.id} | ${escapeMd(t.title)} | ${t.status} | ${t.priority} | ${t.assignee ?? ""} | ${t.created} | ${t.slaDue ?? ""} | ${t.resolved ?? ""} |`).join("\n")}\n`;
}
async function readTickets(dataDir, slug) {
	const p = ticketsPath(dataDir, slug);
	if (!fs.existsSync(p)) return [];
	return parseTicketsFromMarkdown(fs.readFileSync(p, "utf-8"));
}
async function upsertTicket(dataDir, slug, ticket) {
	const p = ticketsPath(dataDir, slug);
	const existing = await readTickets(dataDir, slug);
	const idx = existing.findIndex((t) => t.id === ticket.id);
	if (idx >= 0) existing[idx] = ticket;
	else existing.push(ticket);
	writeFileAtomic(p, serializeTickets(existing));
}
function nextTicketId(tickets) {
	const nums = tickets.map((t) => parseInt(t.id.replace("T-", ""), 10)).filter((n) => !isNaN(n));
	const max = nums.length > 0 ? Math.max(...nums) : 0;
	return `T-${String(max + 1).padStart(3, "0")}`;
}
async function listAllTickets(dataDir, filter) {
	const slugs = filter?.slug ? [filter.slug] : listCustomerSlugs(dataDir);
	const results = (await Promise.all(slugs.map(async (slug) => {
		return (await readTickets(dataDir, slug)).filter((ticket) => (!filter?.status || ticket.status === filter.status) && (!filter?.priority || ticket.priority === filter.priority) && (!filter?.assignee || ticket.assignee === filter.assignee)).map((ticket) => ({
			slug,
			ticket
		}));
	}))).flat();
	const priorityOrder = {
		urgent: 0,
		high: 1,
		normal: 2,
		low: 3
	};
	results.sort((a, b) => {
		const pa = priorityOrder[a.ticket.priority] ?? 2;
		const pb = priorityOrder[b.ticket.priority] ?? 2;
		if (pa !== pb) return pa - pb;
		return a.ticket.created.localeCompare(b.ticket.created);
	});
	return results;
}
//#endregion
export { upsertTicket as i, nextTicketId as n, readTickets as r, listAllTickets as t };

//# sourceMappingURL=ticket-writer-a9on36Wb.js.map