// A PATCH endpoint that takes merge patches, an undo built from the diff, and a change history.
//
//   quillo run json_patch.qwe      then open http://localhost:8080/history

use "json_patch.qwer"

let product = { sku: "B7", name: "Blue mug", price: 12.5, tags: ["kitchen", "blue"], stock: { amsterdam: 4, london: 0 } }

route PATCH /products/b7 = json_merge(product, request.json)

route GET /history {
    let after = json_merge(product, { price: 11.0, tags: ["kitchen", "blue", "sale"], stock: { london: 12 }, name: null })
    let change = json_diff(product, after)?
    let undo = json_diff(after, product)?
    { after, change, undone: json_patch_apply(after, undo)? == product }
}

route GET /apply {
    let patch = [{ op: "test", path: "/price", value: 12.5 }, { op: "replace", path: "/price", value: 9.99 }, { op: "add", path: "/tags/-", value: "gift" }]
    { patched: json_patch_apply(product, patch)?, stale: json_patch_apply(json_merge(product, { price: 13 }), patch).error }
}
