// An audit log of admin actions in which no past entry can be changed unseen.
//
//   quillo run hash_chain.qwe      then open http://localhost:8080/demo

use "hash_chain.qwer"

fn log_action(log: list, who: str, action: str) = [...log, hash_chain_append(log, { who, action })?]

route GET /demo {
    let log = log_action(log_action(log_action([], "ada", "refund order 1042"), "grace", "change price of B7"), "ada", "delete user 77")
    write_file("data/audit.json", json.stringify(log, true))
    let stored = json.parse(read_file("data/audit.json")?)?
    // Someone edits the second entry in the file afterwards.
    let edited = [stored[0], { ...stored[1], data: { who: "grace", action: "change price of B8" } }, stored[2]]
    {
        entries: len(stored),
        last_hash: last(stored).hash,
        intact: hash_chain_verify(stored),
        edited: hash_chain_verify(edited),
        removed: hash_chain_verify([stored[0], stored[2]]).reason,
    }
}
