// A program handing work to AWS Lambda: an invoice rendered by a function and its answer used, a
// function that fails read as a failure with its type and message, a job queued to run later, the
// log tail with its billing line, and the region's functions listed past one page.
//
//   AWS_REGION=eu-west-1 AWS_ACCESS_KEY_ID=... AWS_SECRET_ACCESS_KEY=... quillo run aws_lambda.qwe
//   then open http://localhost:8080/invoke, /failed, /later, /logs, /busy and /list
//
// It wants functions named render-invoice, always-fails and nightly-report. LAMBDA_API_URL reaches
// LocalStack or a test server.

use "aws_lambda.qwer"

route GET /invoke {
    let done = lambda_invoke("render-invoice", { order: 1001, lines: 3 }, { qualifier: "live" })?
    { ok: done.ok, url: done.payload.url, pages: done.payload.pages, version: done.version, direct: lambda_call("render-invoice", { order: 7, lines: 1 }, {})?.url }
}

route GET /failed {
    let run = lambda_invoke("always-fails", { order: 1 }, {})?
    {
        ok: run.ok,
        kind: run.error.kind,
        type: run.error.type,
        message: run.error.message,
        as_error: lambda_call("always-fails", {}, {}).error,
        missing: lambda_invoke("no-such-function", {}, {}).error,
    }
}

route GET /later {
    let id = lambda_invoke_async("nightly-report", { day: "2026-11-01" }, {})?
    { queued: len(id) > 0, allowed: lambda_dry_run("nightly-report", {})?, not_allowed: lambda_dry_run("no-such-function", {}).error }
}

route GET /logs {
    let run = lambda_invoke("render-invoice", { order: 2, lines: 2 }, { log: true, client_context: { custom: { tenant: "acme" } } })?
    let report = lambda_log_report(run.logs)
    { printed: contains(run.logs, "rendering order 2"), tenant: run.payload.tenant, report: report }
}

// The function is at its limit: Lambda says 429 and how long to wait, and the plugin waits.
route GET /busy = { answered: lambda_call("busy-function", {}, {})?.done }

route GET /list {
    let all = lambda_list({ page_size: 2 })?
    let ready = lambda_wait_ready("just-deployed", {})?
    { count: len(all), names: map(all, (f) => f.FunctionName), ready: ready.State, broken: lambda_wait_ready("broken-deploy", {}).error }
}
