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

from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path

from typer.testing import CliRunner

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

runner = CliRunner()


def test_box_list_command_calls_client(monkeypatch, tmp_path: Path) -> None:
    """The box list 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_list(
            self,
            *,
            token: str,
            start_datetime: str | None,
            stop_datetime: str | None,
        ):
            captured["token"] = token
            captured["start"] = start_datetime
            captured["stop"] = stop_datetime
            return [
                {
                    "BoxId": "BOX-1",
                    "BoxName": "Fixture A",
                    "Status": "Active",
                    "StartDateTime": "2026-02-01 00:00:00",
                    "StopDateTime": "2026-02-02T00:00:00Z",
                    "Location": "OrbitOne",
                }
            ]

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

    result = runner.invoke(
        cli.app,
        [
            "box",
            "list",
            "--start",
            "2026-02-01 00:00:00",
            "--stop",
            "2026-02-06 23:59:00",
            "--config-path",
            str(config_path),
        ],
    )

    assert result.exit_code == 0
    assert "BOX-1" in result.stdout
    assert captured == {
        "base_url": "https://qrm.local/api",
        "verify_tls": True,
        "token": "TOKEN123",
        "start": "2026-02-01 00:00:00",
        "stop": "2026-02-06 23:59:00",
    }


def test_box_list_command_supports_json_output(monkeypatch, tmp_path: Path) -> None:
    """Box list should honor --output json."""

    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_list(self, **__: str):  # noqa: ANN003
            return [{"BoxId": "BOX-1"}]

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

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

    assert result.exit_code == 0
    assert json.loads(result.stdout) == [{"BoxId": "BOX-1"}]


def test_box_list_defaults_time_window(monkeypatch, tmp_path: Path) -> None:
    """Box list should default start to the epoch."""

    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())

    fake_start = datetime(1970, 1, 1, 0, 0, tzinfo=timezone.utc)
    fake_stop = None

    def fake_resolver(start, stop):  # noqa: ANN001
        assert start is None and stop is None
        return fake_start, fake_stop

    monkeypatch.setattr("qrm.commands_shared.resolve_box_window", fake_resolver)

    captured = {}

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

        def box_list(self, **kwargs):  # noqa: ANN003
            captured["start"] = kwargs["start_datetime"]
            captured["stop"] = kwargs["stop_datetime"]
            return []

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

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

    assert result.exit_code == 0
    assert captured == {
        "start": "1970-01-01 00:00:00",
        "stop": None,
    }


def test_resolve_box_window_defaults_epoch() -> None:
    """Helper should mirror the epoch default behavior."""

    stop = datetime(2026, 2, 6, 0, 0, tzinfo=timezone.utc)

    start, resolved_stop = resolve_box_window(None, stop)

    assert start == datetime(1970, 1, 1, 0, 0, tzinfo=timezone.utc)
    assert resolved_stop == stop


def test_box_list_handles_empty_payload(monkeypatch, tmp_path: Path) -> None:
    """Empty responses should render a helpful message."""

    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_list(self, **__: str):  # noqa: ANN003
            return []

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

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

    assert result.exit_code == 0
    assert "No results" in result.stdout


def test_box_list_handles_irregular_rows(monkeypatch, tmp_path: Path) -> None:
    """Irregular list entries should still render."""

    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_list(self, **__: str):  # noqa: ANN003
            return [
                {
                    "Id": "BOX-1",
                    "Location": "OrbitOne",
                    "StartDateTime": datetime(2026, 2, 1, 12, 0, tzinfo=timezone.utc),
                    "StopDateTime": None,
                    "Status": "Active",
                },
                123,
            ]

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

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

    assert result.exit_code == 0
    assert "BOX-1" in result.stdout
    assert "123" in result.stdout
