// A shop's feature flags as data: a new checkout rolled out to 20% of users (staff always
// in, one customer always out), a price test with three variants, and a kill switch.
//
//   quillo run feature_flags.qwe      then open http://localhost:8080/flags?user=u-1042&country=NL

use "feature_flags.qwer"

let FLAGS = [
    {
        key: "new_checkout",
        targets: { "u-7": false },
        rules: [
            { name: "staff", when: [{ attr: "email", op: "ends_with", value: "@shop.example" }], serve: true },
            { name: "benelux", when: [{ attr: "country", op: "in", value: ["NL", "BE", "LU"] }], serve: { rollout: [{ value: true, weight: 20 }, { value: false, weight: 80 }] } },
        ],
        serve: false,
    },
    { key: "price_test", serve: { rollout: [{ value: "9.99", weight: 34 }, { value: "11.99", weight: 33 }, { value: "12.99", weight: 33 }] } },
    { key: "reviews", on: false, off: "hidden", serve: "shown" },
]

route GET /flags ? { user: str, country: str = "DE", email: str = "" } = flag_values(FLAGS, { key: user, country, email })?

route GET /why ? { user: str, country: str = "DE", email: str = "" } = FLAGS | map((f) => flag_eval(f, { key: user, country, email })?)

// How 10,000 Dutch users spread over the checkout and the price test, and one user's buckets.
route GET /spread {
    let users = for i in range(10000) => { key: `u-${i}`, country: "NL" }
    {
        checkout: flag_spread(FLAGS[0], users)?,
        price: flag_spread(FLAGS[1], users)?,
        staff: flag_on(FLAGS[0], { key: "u-1", email: "ada@shop.example" })?,
        pinned_out: flag_eval(FLAGS[0], { key: "u-7", email: "x@shop.example" })?.reason,
        bucket: flag_bucket("new_checkout", "u-1042", ""),
        problems: flag_check(FLAGS + [{ key: "reviews", rules: [{ when: [{ attr: "plan", op: "like", value: "pro" }] }] }]),
    }
}
