"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.hasEventHookLedgerEntry = hasEventHookLedgerEntry;
exports.writeEventHookLedgerEntry = writeEventHookLedgerEntry;
const promises_1 = require("node:fs/promises");
const node_path_1 = __importDefault(require("node:path"));
const storage_1 = require("./storage");
async function hasEventHookLedgerEntry(input) {
    const ledger = await readLedger(input);
    return ledger.entries[buildLedgerKey(input)] !== undefined;
}
async function writeEventHookLedgerEntry(input) {
    const ledger = await readLedger(input);
    ledger.entries[buildLedgerKey(input)] = {
        status: input.status,
        eventId: input.eventId,
        hookPath: input.hookPath,
        updatedAt: (input.now ?? new Date()).toISOString(),
        ...(input.summary !== undefined ? { summary: input.summary } : {}),
    };
    const ledgerPath = (0, storage_1.getUserEventHooksLedgerPath)(input);
    await (0, promises_1.mkdir)(node_path_1.default.dirname(ledgerPath), { recursive: true });
    await (0, promises_1.writeFile)(ledgerPath, `${JSON.stringify(ledger, null, 2)}\n`, "utf8");
}
function buildLedgerKey(input) {
    return `${input.eventId}:${input.hookPath}`;
}
async function readLedger(input) {
    const ledgerPath = (0, storage_1.getUserEventHooksLedgerPath)(input);
    let text;
    try {
        text = await (0, promises_1.readFile)(ledgerPath, "utf8");
    }
    catch (error) {
        if (isFileNotFoundError(error)) {
            return { version: 1, entries: {} };
        }
        throw error;
    }
    const parsed = JSON.parse(text);
    return {
        version: 1,
        entries: parsed.entries && typeof parsed.entries === "object"
            ? parsed.entries
            : {},
    };
}
function isFileNotFoundError(error) {
    return (typeof error === "object" &&
        error !== null &&
        "code" in error &&
        error.code === "ENOENT");
}
