import { readPrivateText, writePrivateText } from "./private-storage.js";
const EMPTY = { schemaVersion: 1, transactions: [] };
export function createExecutionJournal(filePath) {
    let serial = Promise.resolve(undefined);
    const locked = (operation) => {
        const result = serial.then(operation, operation);
        serial = result.then(() => undefined, () => undefined);
        return result;
    };
    async function read() {
        const source = await readPrivateText(filePath, "Hatch execution journal");
        if (source === null)
            return structuredClone(EMPTY);
        const value = JSON.parse(source);
        if (value?.schemaVersion !== 1 || !Array.isArray(value.transactions)) {
            throw new Error("Hatch execution journal has an unsupported shape.");
        }
        return value;
    }
    async function write(value) {
        await writePrivateText(filePath, `${JSON.stringify(value, null, 2)}\n`, "Hatch execution journal");
    }
    return {
        read,
        append(receipt) {
            return locked(async () => {
                const value = await read();
                value.transactions.push(structuredClone(receipt));
                await write(value);
                return structuredClone(receipt);
            });
        },
        update(transactionId, update) {
            return locked(async () => {
                const value = await read();
                const index = value.transactions.findIndex((item) => item.transactionId === transactionId);
                if (index < 0)
                    throw new Error(`Unknown Hatch transaction ${transactionId}.`);
                value.transactions[index] = update(structuredClone(value.transactions[index]));
                await write(value);
                return structuredClone(value.transactions[index]);
            });
        },
    };
}
