import neo4j from "neo4j-driver";
import { getSession } from "../lib/neo4j.js";
const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
function padDateBound(value, end) {
    if (!DATE_ONLY.test(value))
        return value;
    return end === "start"
        ? `${value}T00:00:00.000Z`
        : `${value}T23:59:59.999Z`;
}
export async function scheduleList(params) {
    const { accountId, status, from, to, upcoming, limit = 50 } = params;
    const effectiveFrom = from ? padDateBound(from, "start") : undefined;
    const effectiveTo = to ? padDateBound(to, "end") : undefined;
    if (effectiveFrom || effectiveTo) {
        console.log(`[schedule-list] filter: from=${effectiveFrom ?? "(none)"} to=${effectiveTo ?? "(none)"}`);
    }
    const conditions = ["e.accountId = $accountId"];
    const queryParams = {
        accountId,
        limit: neo4j.int(limit),
    };
    if (status) {
        conditions.push("e.eventStatus = $status");
        queryParams.status = status;
    }
    if (effectiveFrom && effectiveTo) {
        conditions.push("((e.startDate >= $from AND e.startDate <= $to) OR (e.nextRun IS NOT NULL AND e.nextRun >= $from AND e.nextRun <= $to))");
        queryParams.from = effectiveFrom;
        queryParams.to = effectiveTo;
    }
    else if (effectiveFrom) {
        conditions.push("(e.startDate >= $from OR (e.nextRun IS NOT NULL AND e.nextRun >= $from))");
        queryParams.from = effectiveFrom;
    }
    else if (effectiveTo) {
        conditions.push("(e.startDate <= $to OR (e.nextRun IS NOT NULL AND e.nextRun <= $to))");
        queryParams.to = effectiveTo;
    }
    if (upcoming) {
        conditions.push("e.eventStatus IN ['scheduled', 'due']");
        conditions.push("(e.startDate >= $now OR e.nextRun IS NOT NULL)");
        queryParams.now = new Date().toISOString();
    }
    const where = conditions.join(" AND ");
    const neo4jSession = getSession();
    try {
        const result = await neo4jSession.run(`MATCH (e:Event)
       WHERE ${where}
       RETURN e
       ORDER BY COALESCE(e.nextRun, e.startDate) ASC
       LIMIT $limit`, queryParams);
        return result.records.map((r) => {
            const e = r.get("e").properties;
            const summary = {
                eventId: e.eventId,
                name: e.name,
                startDate: e.startDate,
                eventStatus: e.eventStatus,
            };
            if (e.endDate)
                summary.endDate = e.endDate;
            if (e.recurrence)
                summary.recurrence = e.recurrence;
            if (e.nextRun)
                summary.nextRun = e.nextRun;
            if (e.location)
                summary.location = e.location;
            return summary;
        });
    }
    finally {
        await neo4jSession.close();
    }
}
//# sourceMappingURL=schedule-list.js.map