from __future__ import annotations

from aegro.cli import app


class TestNfeXml:
    def test_download_xml(self, runner, mock_settings, mock_client, temp_state, tmp_path):
        mock_client.download.return_value = b"<xml>content</xml>"
        runner.invoke(app, ["farms", "select", "Fazenda Sul"])
        out = tmp_path / "nfe.xml"
        result = runner.invoke(
            app,
            [
                "nfes",
                "xml",
                "35250512345678000190550010000123451234567890",
                "-o",
                str(out),
            ],
        )
        assert result.exit_code == 0
        assert out.read_bytes() == b"<xml>content</xml>"
        mock_client.download.assert_called_once_with(
            "/pub/v1/nfes/35250512345678000190550010000123451234567890/xml",
            api_key="key-1",
        )

    def test_download_not_found(self, runner, mock_settings, mock_client, temp_state, tmp_path):
        mock_client.download.return_value = None
        runner.invoke(app, ["farms", "select", "Fazenda Sul"])
        out = tmp_path / "nfe.xml"
        result = runner.invoke(app, ["nfes", "xml", "35250512345678", "-o", str(out)])
        assert result.exit_code == 0
        assert "nao encontrad" in result.stdout.lower()


class TestNfeXmlBatch:
    def test_batch(self, runner, mock_settings, mock_client, temp_state, tmp_path):
        mock_client.download.return_value = b"PK\x03\x04zipcontent"
        runner.invoke(app, ["farms", "select", "Fazenda Sul"])
        out = tmp_path / "nfes.zip"
        result = runner.invoke(
            app,
            [
                "nfes",
                "xml-batch",
                "-o",
                str(out),
                "--start-date",
                "2025-01-01",
                "--end-date",
                "2025-01-31",
                "--operation-type",
                "OUTBOUND",
                "--status",
                "AUTHORIZED",
            ],
        )
        assert result.exit_code == 0
        assert out.read_bytes().startswith(b"PK")
        call = mock_client.download.call_args
        assert call.args[0] == "/pub/v1/nfes/xmls/filter"
        assert call.kwargs["method"] == "POST"
        body = call.kwargs["json_body"]
        assert body["startDate"] == "2025-01-01"
        assert body["endDate"] == "2025-01-31"
        assert body["operationTypes"] == ["OUTBOUND"]
        assert body["statuses"] == ["AUTHORIZED"]
