use std::fs;
use std::path::PathBuf;

use rpki::source::pipeline::{PayloadLoadConfig, load_payloads_from_latest_sources};
use tempfile::tempdir;

fn data_dir() -> String {
    PathBuf::from(env!("CARGO_MANIFEST_DIR"))
        .join("data")
        .to_string_lossy()
        .to_string()
}

#[test]
fn load_payloads_rejects_entire_slurm_set_when_any_file_is_invalid() {
    let slurm_dir = tempdir().expect("create temp slurm dir");

    let valid = r#"{
        "slurmVersion": 1,
        "validationOutputFilters": {
            "prefixFilters": [],
            "bgpsecFilters": []
        },
        "locallyAddedAssertions": {
            "prefixAssertions": [],
            "bgpsecAssertions": []
        }
    }"#;

    fs::write(slurm_dir.path().join("01-valid.slurm"), valid).expect("write valid slurm");
    fs::write(slurm_dir.path().join("02-invalid.slurm"), "{").expect("write invalid slurm");

    let config = PayloadLoadConfig {
        ccr_dir: data_dir(),
        slurm_dir: Some(slurm_dir.path().to_string_lossy().to_string()),
        strict_ccr_validation: false,
    };

    let err = load_payloads_from_latest_sources(&config).unwrap_err();
    let text = err.to_string();
    assert!(text.contains("failed to parse SLURM file"));
    assert!(text.contains("02-invalid.slurm"));
}
