use betex::{
    book::protocol::command::{Command, CommandKind, MarketState},
    book::protocol::reject::RejectReason,
    config::Config,
    engine::{
        root::EngineRoot,
        state::{EngineState, Market},
    },
    types::*,
};
mod common;
use common::{apply_outcome, two_runner_market_config};

#[test]
fn cannot_reopen_terminal_market_via_set_market_state() {
    let cfg = Config::default();
    let mut state = EngineState::new(cfg);
    let _ts = unix_epoch();

    let market_id = MarketId(1);
    state.markets.insert(
        market_id,
        Market::from_config_with_cfg(&state.cfg, two_runner_market_config(market_id)),
    );
    let mut root = EngineRoot::new_with(state, 0);

    // Close then void to reach terminal state.
    for (correlation_id, kind) in [
        (
            1u64,
            CommandKind::SetMarketState {
                state: MarketState::Closed,
            },
        ),
        (
            2u64,
            CommandKind::VoidMarket {
                reason: "TEST_VOID".to_string(),
            },
        ),
    ] {
        let cmd = Command {
            correlation_id: Some(CorrelationId(correlation_id.to_string())),
            metadata: None,
            market_id,
            kind,
        };
        root.handle(cmd).expect("command handler succeeds");
        let events = root.take_changes();
        apply_outcome(&mut root, events);
    }

    // Attempt to reopen should be rejected (book enforces MarketTerminal).
    let reopen = Command {
        correlation_id: Some(CorrelationId(3.to_string())),
        metadata: None,
        market_id,
        kind: CommandKind::SetMarketState {
            state: MarketState::Open,
        },
    };
    let before_seq = root.version();
    let err = root
        .handle(reopen)
        .expect_err("reopening a terminal market should be rejected");
    assert_eq!(err.into_reason(), RejectReason::MarketTerminal);
    assert_eq!(root.version(), before_seq);
}
