#[path = "../support/utils.rs"]
mod _utils;

use _utils::{boxed_error, cleanup_run, create_client, new_run_id, print_summary, require};
use mubit_sdk::{RememberOptions, TransportMode};
use serde_json::{json, Value};
use std::error::Error;
use std::time::Instant;
use tokio::time::{sleep, Duration};

#[tokio::main(flavor = "current_thread")]
async fn main() -> Result<(), Box<dyn Error>> {
    let name = "internal_lessons_lifecycle";
    let started = Instant::now();
    let client = create_client().await?;
    let run_id = new_run_id("internal_lessons_lifecycle");
    client.set_run_id(Some(run_id.clone()));
    client.set_transport(TransportMode::Http);
    let mut passed = true;
    let mut detail = "validated raw lessons lifecycle".to_string();
    let mut metrics = json!({});

    let scenario = async {
        let mut remember = RememberOptions::new("Always verify the stored deductible before approving reimbursement.");
        remember.run_id = Some(run_id.clone());
        remember.intent = Some("lesson".into());
        remember.lesson_type = Some("success".into());
        remember.lesson_scope = Some("session".into());
        client.remember(remember).await?;

        let mut lessons = serde_json::Value::Null;
        for _ in 0..24 {
            let current = client
                .control
                .lessons(json!({"run_id": run_id, "limit": 10}))
                .await?;
            let has_lesson = current
                .get("lessons")
                .and_then(|v| v.as_array())
                .map(|items| !items.is_empty())
                .unwrap_or(false);
            lessons = current;
            if has_lesson {
                break;
            }
            sleep(Duration::from_millis(500)).await;
        }
        let lesson_id = lessons.get("lessons").and_then(|v| v.as_array()).and_then(|items| items.iter().find_map(|item| item.get("id").and_then(|v| v.as_str()))).ok_or_else(|| boxed_error(format!("expected lesson in lifecycle test: {lessons}")))?.to_string();
        let deleted = client.control.delete_lesson(json!({"lesson_id": lesson_id})).await?;
        let remaining = client.control.lessons(json!({"run_id": run_id, "limit": 10})).await?;
        require(deleted.get("success").and_then(Value::as_bool).unwrap_or(true), format!("delete_lesson failed: {deleted}"))?;
        require(!remaining.get("lessons").and_then(|v| v.as_array()).map(|items| items.iter().any(|item| item.get("id").and_then(|v| v.as_str()) == Some(lesson_id.as_str()))).unwrap_or(false), format!("lesson still present after delete: {remaining}"))?;
        metrics = json!({"run_id": run_id, "lesson_id": lesson_id});
        Ok::<(), Box<dyn Error>>(())
    }.await;

    if let Err(err) = scenario { passed = false; detail = err.to_string(); }
    let cleanup_ok = cleanup_run(&client, &run_id).await;
    if !cleanup_ok { passed = false; detail = format!("{detail} | cleanup failures"); }
    print_summary(name, passed, &detail, &metrics, started.elapsed().as_secs_f64(), cleanup_ok);
    if passed { Ok(()) } else { Err(boxed_error(detail)) }
}
