//! `pic apply` journey: apply a manifest to an empty app (atomic create),
//! re-apply is an idempotent no-op, and a bundle containing any invalid
//! resource applies nothing (all-or-nothing).

use std::fs;

use tempfile::TempDir;

use crate::common;
use crate::common::cleanup::AppGuard;

fn manifest_dir() -> TempDir {
    let dir = TempDir::new().expect("tempdir");
    fs::create_dir_all(dir.path().join("scripts")).expect("scripts dir");
    dir
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn apply_creates_then_noop() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let slug = common::unique_slug("apply");
    common::pic_as(&env)
        .args(["apps", "create", &slug])
        .assert()
        .success();
    let _guard = AppGuard::new(&env.url, &env.token, &slug);

    let dir = manifest_dir();
    fs::write(
        dir.path().join("scripts/greet.rhai"),
        "let body = #{ ok: true }; body",
    )
    .unwrap();
    let manifest = format!(
        "[app]\nslug = \"{slug}\"\nname = \"Apply Test\"\n\n\
         [[scripts]]\nname = \"greet\"\nfile = \"scripts/greet.rhai\"\n\n\
         [[routes]]\nscript = \"greet\"\nmethod = \"POST\"\n\
         host_kind = \"any\"\npath_kind = \"exact\"\npath = \"/greet\"\n\n\
         [[triggers.cron]]\nscript = \"greet\"\nschedule = \"0 0 * * * *\"\ntimezone = \"UTC\"\n"
    );
    let manifest_path = dir.path().join("picloud.toml");
    fs::write(&manifest_path, &manifest).unwrap();

    // First apply: creates script + route + trigger.
    let out = common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&manifest_path)
        .output()
        .expect("apply");
    assert!(
        out.status.success(),
        "apply failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let stdout = String::from_utf8(out.stdout).unwrap();
    assert!(
        stdout.contains("+1"),
        "expected creations in report:\n{stdout}"
    );

    // The resources now exist.
    let s = String::from_utf8(
        common::pic_as(&env)
            .args(["scripts", "ls", "--app", &slug])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(s.contains("greet"), "script not created:\n{s}");

    // Plan is now clean (apply reached desired state).
    let p = String::from_utf8(
        common::pic_as(&env)
            .args(["plan", "--file"])
            .arg(&manifest_path)
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        !p.contains("create") && !p.contains("update"),
        "expected clean plan after apply:\n{p}"
    );

    // Re-apply: idempotent — nothing created/updated.
    let r = String::from_utf8(
        common::pic_as(&env)
            .args(["apply", "--file"])
            .arg(&manifest_path)
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(!r.contains("+1"), "re-apply should be a no-op:\n{r}");
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn apply_rejects_bad_bundle_atomically() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let slug = common::unique_slug("apply-atomic");
    common::pic_as(&env)
        .args(["apps", "create", &slug])
        .assert()
        .success();
    let _guard = AppGuard::new(&env.url, &env.token, &slug);

    let dir = manifest_dir();
    fs::write(dir.path().join("scripts/good.rhai"), "let x = 1; x").unwrap();
    // Invalid Rhai — fails validation, so the whole apply must abort.
    fs::write(dir.path().join("scripts/bad.rhai"), "let x = ;").unwrap();
    let manifest = format!(
        "[app]\nslug = \"{slug}\"\nname = \"Atomic Test\"\n\n\
         [[scripts]]\nname = \"good\"\nfile = \"scripts/good.rhai\"\n\n\
         [[scripts]]\nname = \"bad\"\nfile = \"scripts/bad.rhai\"\n"
    );
    let manifest_path = dir.path().join("picloud.toml");
    fs::write(&manifest_path, &manifest).unwrap();

    let out = common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&manifest_path)
        .output()
        .expect("apply");
    assert!(
        !out.status.success(),
        "apply with an invalid script should fail"
    );

    // Atomic: the valid script must NOT have been created.
    let s = String::from_utf8(
        common::pic_as(&env)
            .args(["scripts", "ls", "--app", &slug])
            .output()
            .unwrap()
            .stdout,
    )
    .unwrap();
    assert!(
        !s.contains("good"),
        "a failed apply must leave nothing behind:\n{s}"
    );
}

#[ignore = "needs DATABASE_URL pointing at a running Postgres"]
#[test]
fn apply_reconciles_app_vars() {
    let Some(fx) = common::fixture_or_skip() else {
        return;
    };
    let env = common::admin_env(fx);
    let slug = common::unique_slug("apply-vars");
    common::pic_as(&env)
        .args(["apps", "create", &slug])
        .assert()
        .success();
    let _guard = AppGuard::new(&env.url, &env.token, &slug);

    let dir = manifest_dir();
    // The script returns the resolved `region` var verbatim, so an invoke
    // reflects exactly what `apply` wrote.
    fs::write(
        dir.path().join("scripts/read.rhai"),
        "vars::get(\"region\")",
    )
    .unwrap();
    let manifest = |vars_block: &str| {
        format!(
            "[app]\nslug = \"{slug}\"\nname = \"Vars Test\"\n\n\
             [[scripts]]\nname = \"read\"\nfile = \"scripts/read.rhai\"\n\n\
             [[routes]]\nscript = \"read\"\nmethod = \"POST\"\n\
             host_kind = \"any\"\npath_kind = \"exact\"\npath = \"/read\"\n\n\
             {vars_block}"
        )
    };
    let manifest_path = dir.path().join("picloud.toml");

    // 1. Apply with `region = "eu"` → the var is created and injected.
    fs::write(&manifest_path, manifest("[vars]\nregion = \"eu\"\n")).unwrap();
    let out = common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&manifest_path)
        .output()
        .expect("apply");
    assert!(
        out.status.success(),
        "apply failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    let id = script_id(&env, &slug);
    assert_eq!(
        invoke_body(&env, &id),
        serde_json::json!("eu"),
        "var applied"
    );

    // 2. Change the value → Update (not Create).
    fs::write(&manifest_path, manifest("[vars]\nregion = \"us\"\n")).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&manifest_path)
        .assert()
        .success();
    assert_eq!(
        invoke_body(&env, &id),
        serde_json::json!("us"),
        "var updated"
    );

    // 3. Drop the var + `--prune` → Delete; `vars::get` now returns `()`.
    fs::write(&manifest_path, manifest("")).unwrap();
    common::pic_as(&env)
        .args(["apply", "--file"])
        .arg(&manifest_path)
        .args(["--prune", "--yes"])
        .assert()
        .success();
    assert_eq!(
        invoke_body(&env, &id),
        serde_json::Value::Null,
        "var pruned → unresolved"
    );
}

fn script_id(env: &common::TestEnv, slug: &str) -> String {
    let ls = common::pic_as(env)
        .args(["scripts", "ls", "--app", slug])
        .output()
        .expect("scripts ls");
    common::parse_first_id(std::str::from_utf8(&ls.stdout).unwrap())
        .expect("scripts ls should produce one row")
}

fn invoke_body(env: &common::TestEnv, id: &str) -> serde_json::Value {
    let out = common::pic_as(env)
        .args(["scripts", "invoke", id])
        .output()
        .expect("scripts invoke");
    assert!(
        out.status.success(),
        "invoke failed: {}",
        String::from_utf8_lossy(&out.stderr)
    );
    serde_json::from_slice(&out.stdout).expect("invoke body is JSON")
}
