import datetime
import json
from pathlib import Path

import pytest
from typer.testing import CliRunner
from qrm.query_commands import query_app
from qrm.client import LoginState, QrmClientError
import typer

runner = CliRunner()


def make_fake_state(tmp_path):
    state = LoginState(
        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())
    return state, config_path


class FakeClient:
    def __init__(self, base_url: str, verify_tls: bool) -> None:
        self.base_url = base_url
        self.verify_tls = verify_tls
        self.called = {}

    def export_sql(self, token, query, format, parameters):
        self.called = {
            "token": token,
            "query": query,
            "format": format,
            "parameters": parameters,
        }
        return {"result": "ok", "parameters": parameters}


def test_query_serial_command(monkeypatch, tmp_path):
    state, config_path = make_fake_state(tmp_path)
    fake_client = FakeClient(state.base_url, state.verify_tls)
    monkeypatch.setattr("qrm.query_commands.QrmClient", lambda *a, **kw: fake_client)

    serial_number = "SN123456789"
    result = runner.invoke(
        query_app,
        [
            "serial",
            serial_number,
            "--config-path",
            str(config_path),
            "--output",
            "json",
        ],
    )
    assert result.exit_code == 0
    out = json.loads(result.stdout)
    assert out["result"] == "ok"
    assert fake_client.called["parameters"]["serial_number"] == serial_number
    assert "tResultSet" in fake_client.called["query"]
    assert fake_client.called["format"] == "json"
