// Orders saved by a Java service as length-delimited protobuf: read without its generated code, first raw, then by field name; and one encoded back.
//
//   quillo run protobuf_wire.qwe      then open http://localhost:8080/orders

use "protobuf_wire.qwer"

// The fields of shop.Order, as its .proto file numbers them.
let ORDER = {
    "1": "id int64",
    "2": "customer string",
    "3": { name: "lines", repeated: true, fields: { "1": "sku string", "2": "qty int32", "3": "price_cents sint64" } },
    "4": "paid bool",
    "5": "total double",
    "6": "repeated tags string",
}

route GET /orders {
    let messages = protobuf_split_delimited(protobuf_read_file("protobuf_wire_sample.bin")?)?
    messages | map((m) => protobuf_decode_with(m, ORDER)?)
}

// What the first order looks like with no schema at all.
route GET /raw {
    let first = protobuf_split_delimited(protobuf_read_file("protobuf_wire_sample.bin")?)?[0]
    protobuf_decode(first)?
}

route GET /encode {
    let b64 = protobuf_encode_with({ id: 7, customer: "Zoë", lines: [{ sku: "A", qty: 1, price_cents: -3 }], paid: true, total: 2.5, tags: ["x"] }, ORDER)?
    { base64: b64, back: protobuf_decode_with(b64, ORDER)?, unknown_name: protobuf_encode_with({ colour: "red" }, ORDER).error }
}
