//! Create an export for the last hour and print download artifacts once ready.
//!
//! Run: `TICKSUPPLY_API_KEY=... cargo run --example create_export -- <datastream_id>`

use std::env;
use std::time::Duration;

use chrono::{Duration as ChronoDuration, Utc};
use ticksupply::resources::exports::ExportStatus;

#[tokio::main]
async fn main() -> ticksupply::Result<()> {
    let datastream_id: i64 = env::args()
        .nth(1)
        .expect("pass a datastream id")
        .parse()
        .expect("datastream id must be integer");

    let client = ticksupply::Client::new()?;
    let now = Utc::now();
    // The server requires a UUID (any version) as the idempotency key. In
    // production, persist this value so retries of the same logical export
    // get collapsed server-side.
    let idem = uuid::Uuid::new_v4().to_string();
    let job = client
        .exports()
        .create(datastream_id, now - ChronoDuration::hours(1), now)
        .idempotency_key(&idem)
        .send()
        .await?;

    println!("created {} ({:?})", job.id, job.status);

    loop {
        let job = client.exports().get(&job.id).await?;
        match job.status {
            ExportStatus::Succeeded => {
                let d = client.exports().get_download(&job.id).await?;
                for a in d.artifacts {
                    println!("{} ({} bytes) -> {}", a.filename, a.bytes, a.url);
                }
                break;
            }
            ExportStatus::Failed => {
                eprintln!("failed: {:?}", job.reason);
                break;
            }
            _ => {
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        }
    }
    Ok(())
}
