use mnote_editor_core::{BlockType, DocumentBlock, DocumentModel, EditorCommand, EditorSession};

#[test]
fn history_undo_redo_restores_command_sequence() {
    let mut session = EditorSession::new(DocumentModel::new(vec![DocumentBlock::new(
        "block_a",
        BlockType::Paragraph,
    )
    .with_text("hello")]));

    session
        .apply_command(EditorCommand::ReplaceBlock {
            block_id: "block_a".into(),
            text: "hello world".into(),
        })
        .expect("replace should succeed");
    session
        .apply_command(EditorCommand::InsertBlockAfter {
            after_block_id: Some("block_a".into()),
            block: DocumentBlock::new("block_b", BlockType::Paragraph).with_text("tail"),
        })
        .expect("insert should succeed");

    assert_eq!(session.document().blocks().len(), 2);
    assert!(session.undo());
    assert_eq!(session.document().blocks().len(), 1);
    assert_eq!(
        session
            .document()
            .block("block_a")
            .expect("block_a after undo")
            .content
            .text,
        "hello world"
    );
    assert!(session.undo());
    assert_eq!(
        session
            .document()
            .block("block_a")
            .expect("block_a after second undo")
            .content
            .text,
        "hello"
    );
    assert!(session.redo());
    assert!(session.redo());
    assert_eq!(session.document().blocks().len(), 2);
}

#[test]
fn history_clears_redo_after_new_command() {
    let mut session = EditorSession::new(DocumentModel::new(vec![DocumentBlock::new(
        "block_a",
        BlockType::Paragraph,
    )
    .with_text("hello")]));

    session
        .apply_command(EditorCommand::ReplaceBlock {
            block_id: "block_a".into(),
            text: "hello world".into(),
        })
        .expect("replace should succeed");
    assert!(session.undo());
    session
        .apply_command(EditorCommand::InsertBlockAfter {
            after_block_id: Some("block_a".into()),
            block: DocumentBlock::new("block_b", BlockType::Paragraph).with_text("fresh"),
        })
        .expect("insert should succeed");

    assert!(!session.redo());
    assert_eq!(session.document().blocks().len(), 2);
}
