use super::common::bucketwarden;

#[test]
fn config_validate_rejects_empty_key_material() {
    let path = std::env::temp_dir().join(format!(
        "bucketwarden-invalid-operator-{}.json",
        std::process::id()
    ));
    std::fs::write(
        &path,
        r#"{"key_id":"test-key","key_material":"","clock_epoch_seconds":42}"#,
    )
    .unwrap();

    let output = bucketwarden()
        .args(["config", "validate", "--config"])
        .arg(&path)
        .output()
        .unwrap();
    let _ = std::fs::remove_file(&path);

    assert_eq!(output.status.code(), Some(1));
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("config key_material must not be empty"));
}

#[test]
fn missing_config_usage_exits_with_usage_code() {
    let output = bucketwarden().args(["config"]).output().unwrap();

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("missing config command"));
}

#[test]
fn unknown_command_exits_with_usage_error() {
    let output = bucketwarden().arg("serve").output().unwrap();

    assert_eq!(output.status.code(), Some(2));
    let stderr = String::from_utf8(output.stderr).unwrap();
    assert!(stderr.contains("unknown command `serve`"));
    assert!(stderr.contains("bucketwarden --help"));
}

#[test]
fn unknown_or_incomplete_feature_flags_exit_with_usage_error() {
    let explain = bucketwarden()
        .args([
            "policy",
            "explain",
            "--principal",
            "alice",
            "--action",
            "s3:GetObject",
            "--resource",
            "archive/a.txt",
            "--dry-run",
        ])
        .output()
        .unwrap();
    assert_eq!(explain.status.code(), Some(2));
    assert!(String::from_utf8(explain.stderr)
        .unwrap()
        .contains("unknown policy explain flag `--dry-run`"));

    let rotate = bucketwarden()
        .args([
            "auth",
            "key",
            "rotate",
            "--principal",
            "alice",
            "--old",
            "AKIAOLD",
            "--new",
            "AKIANEW",
            "--secret",
        ])
        .output()
        .unwrap();
    assert_eq!(rotate.status.code(), Some(2));
    assert!(String::from_utf8(rotate.stderr)
        .unwrap()
        .contains("missing value for `--secret`"));

    let ops = bucketwarden()
        .args(["ops", "report", "health", "--extra", "value"])
        .output()
        .unwrap();
    assert_eq!(ops.status.code(), Some(2));
    assert!(String::from_utf8(ops.stderr)
        .unwrap()
        .contains("unknown ops report flag `--extra`"));
}
