"""Tests for quit command."""

from unittest.mock import MagicMock, patch

import pytest

from mudlib.commands.quit import cmd_quit
from mudlib.player import players


@pytest.fixture
def mock_writer():
    """Override conftest mock_writer to add close method for quit tests."""
    from unittest.mock import AsyncMock

    writer = MagicMock()
    writer.write = MagicMock()
    writer.drain = AsyncMock()
    writer.close = MagicMock()
    return writer


@pytest.mark.asyncio
async def test_quit_blocked_during_combat(player):
    """Test quit is blocked when player is in combat mode."""
    player.mode_stack.append("combat")

    await cmd_quit(player, "")

    player.writer.write.assert_called_once_with("You can't quit during combat!\r\n")
    player.writer.close.assert_not_called()
    assert player.name in players  # Still in player registry


@pytest.mark.asyncio
async def test_quit_works_when_not_in_combat(player):
    """Test quit works normally when not in combat."""
    # Player starts in "normal" mode by default

    with patch("mudlib.commands.quit.save_player"):
        await cmd_quit(player, "")

    # Should write goodbye message
    player.writer.write.assert_called_with("Goodbye!\r\n")
    player.writer.drain.assert_called_once()
    player.writer.close.assert_called_once()
    assert player.name not in players  # Removed from registry
    assert player.location is None  # Removed from zone
