// A table in Airtable as a contact list: records read past their pages, written in batches of 10,
// upserted by email, found by a formula with a visitor's text safely quoted.
//
//   AIRTABLE_TOKEN=... AIRTABLE_BASE=appXXXXXXXXXXXXXX quillo run airtable.qwe
//   then open http://localhost:8080/import, /all, /upsert, /find and /failures
//
// The table here is called "Contacts", with the fields Email, Name and Visits.

use "airtable.qwer"

let BASE = env("AIRTABLE_BASE", "")
let TABLE = "Contacts"

route GET /import {
    let rows = map(range(0, 23), (i) => { Email: `p${i}@example.com`, Name: `Person ${i}`, Visits: i })
    let made = airtable_create(BASE, TABLE, rows, { typecast: true })?
    let changed = airtable_update(BASE, TABLE, [{ id: made[0].id, fields: { Visits: 99 } }], {})?
    let gone = airtable_delete(BASE, TABLE, map(made, (r) => r.id), {})?
    { made: len(made), first: made[0].fields.Name, changed: changed[0].fields.Visits, deleted: gone }
}

route GET /all {
    let one = airtable_list(BASE, "Big table", { page_size: 2, sort: [{ field: "Rank", direction: "desc" }], fields: ["Rank"] })?
    let rows = airtable_rows(airtable_all(BASE, "Big table", {})?)
    { first_page: len(one.records), more: one.offset != null, total: len(rows), top: one.records[0].fields.Rank, row: rows[0].Rank }
}

route GET /upsert {
    let rows = map(range(0, 12), (i) => { Email: `u${i}@example.com`, Name: `U ${i}` })
    let first = airtable_upsert(BASE, TABLE, rows, ["Email"], {})?
    let second = airtable_upsert(BASE, TABLE, [{ Email: "u0@example.com", Name: "Changed" }, { Email: "new@example.com", Name: "New" }], ["Email"], {})?
    { created: len(first.created), updated: len(first.updated), then_created: len(second.created), then_updated: len(second.updated) }
}

route GET /find {
    airtable_create(BASE, TABLE, [{ Email: "o'brien@example.com", Name: "Sean" }], {})?
    let formula = "{Email} = " + airtable_quote("o'brien@example.com")
    let hit = airtable_all(BASE, TABLE, { formula: formula })?
    { formula: formula, name: hit[0].fields.Name, nasty: airtable_quote("' OR 1 = 1 OR 'a\\") }
}

route GET /failures = {
    unknown_field: airtable_create(BASE, TABLE, [{ Nope: 1 }], {}).error,
    no_table: airtable_list(BASE, "Missing", {}).error,
    bad_token: airtable_list(BASE, TABLE, { token: "wrong" }).error,
    expired: airtable_list(BASE, TABLE, { offset: "stale" }).error,
    merge_on_four: airtable_upsert(BASE, TABLE, [{ a: 1 }], ["a", "b", "c", "d"], {}).error,
    merge_field: airtable_upsert(BASE, TABLE, [{ Name: "x" }], ["Email"], {}).error,
    no_id: airtable_update(BASE, TABLE, [{ fields: {} }], {}).error,
    waited: len(airtable_create(BASE, TABLE, [{ Email: "rate@example.com", Name: "rate me" }], { retry_wait_ms: 300 })?),
}
