//! REQUIREMENT: VAL-004 — Missing coin rejected; coin in records passes

mod common;

use std::collections::{HashMap, HashSet};

use chia_bls::Signature;
use chia_protocol::{Bytes32, SpendBundle};
use dig_clvm::{validate_spend_bundle, ValidationContext, ValidationError, DIG_TESTNET};

use common::{
    create_coin_condition, make_context, make_simple_spend, test_config, wrap_conditions,
};

#[test]
fn val_004_missing_coin_rejected() {
    let parent = Bytes32::from([0x04; 32]);
    let output_ph = [0x05; 32];
    let cond = create_coin_condition(&output_ph, 500);
    let solution = wrap_conditions(&[cond]);
    let spend = make_simple_spend(parent, 1000, &solution);

    let bundle = SpendBundle::new(vec![spend], Signature::default());
    // Empty context — no coins
    let context = ValidationContext {
        height: 1,
        timestamp: 1000,
        constants: DIG_TESTNET.clone(),
        coin_records: HashMap::new(),
        ephemeral_coins: HashSet::new(),
    };
    let config = test_config();

    let result = validate_spend_bundle(&bundle, &context, &config, None);
    assert!(result.is_err());
    match result {
        Err(ValidationError::CoinNotFound(_)) => {} // expected
        Err(other) => panic!("expected CoinNotFound, got {:?}", other),
        Ok(_) => panic!("expected error, got Ok"),
    }
}

#[test]
fn val_004_coin_in_records_passes() {
    let parent = Bytes32::from([0x04; 32]);
    let output_ph = [0x05; 32];
    let cond = create_coin_condition(&output_ph, 500);
    let solution = wrap_conditions(&[cond]);
    let spend = make_simple_spend(parent, 1000, &solution);
    let coin = spend.coin;

    let bundle = SpendBundle::new(vec![spend], Signature::default());
    let context = make_context(&[coin]);
    let config = test_config();

    let result = validate_spend_bundle(&bundle, &context, &config, None);
    assert!(
        result.is_ok(),
        "expected Ok, got {:?}",
        result.as_ref().err()
    );
}
