"""Tests for the 'box delete' command."""

from __future__ import annotations

import json
from pathlib import Path

from typer.testing import CliRunner

from qrm import cli
from qrm import box_commands
from qrm.client import LoginState

runner = CliRunner()


def test_box_delete_command_calls_client(monkeypatch, tmp_path: Path) -> None:
    """The box delete subcommand should call its API helper."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    captured = {}

    class FakeClient:
        def __init__(self, base_url: str, verify_tls: bool) -> None:  # noqa: D401
            captured["base_url"] = base_url
            captured["verify_tls"] = verify_tls

        def box_remove(
            self,
            *,
            token: str,
            box_identifier: str,
        ):
            captured["token"] = token
            captured["box_identifier"] = box_identifier
            return True

    monkeypatch.setattr(box_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "box",
            "delete",
            "BOX-001",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 0
    assert captured == {
        "base_url": "https://qrm.local/api",
        "verify_tls": True,
        "token": "TOKEN123",
        "box_identifier": "BOX-001",
    }


def test_box_delete_command_supports_json_output(monkeypatch, tmp_path: Path) -> None:
    """Box delete should emit raw JSON when requested."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    class FakeClient:
        def __init__(self, *_: str, **__: str) -> None:  # noqa: D401, ANN001, ANN002, ANN003
            pass

        def box_remove(
            self,
            *,
            token: str,
            box_identifier: str,
        ):
            return True

    monkeypatch.setattr(box_commands, "QrmClient", FakeClient)

    result = runner.invoke(
        cli.app,
        [
            "box",
            "delete",
            "BOX-001",
            "--config-path",
            str(config_path),
            "--output",
            "json",
        ],
    )

    assert result.exit_code == 0
    assert json.loads(result.stdout) is True


def test_box_delete_command_handles_client_errors(monkeypatch, tmp_path: Path) -> None:
    """Box delete errors should surface as helpful messages with exit code 1."""

    state = LoginState(  # type: ignore[call-arg]
        token="TOKEN123",
        username="alice",
        base_url="https://qrm.local/api",
        verify_tls=True,
    )
    config_path = tmp_path / "login.json"
    config_path.write_text(state.model_dump_json())

    class ExplodingClient:
        def __init__(self, *_, **__):  # noqa: D401, ANN002, ANN003
            pass

        def box_remove(self, **__):  # noqa: ANN003
            raise cli.QrmClientError("API error")

    monkeypatch.setattr(box_commands, "QrmClient", ExplodingClient)

    result = runner.invoke(
        cli.app,
        [
            "box",
            "delete",
            "BOX-ERROR",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 1
    assert "Box delete failed" in result.stdout
