"""Tests for appxen login command."""

from unittest.mock import patch

from typer.testing import CliRunner

from appxen_cli.main import app


class TestLogin:

    def test_invalid_key_format(self):
        """Login rejects keys that don't start with axgw_."""
        runner = CliRunner()
        result = runner.invoke(app, ["login"], input="bad_key\n")
        assert result.exit_code == 1
        assert "Invalid API key" in result.output

    def test_empty_key(self):
        """Login rejects empty key."""
        runner = CliRunner()
        result = runner.invoke(app, ["login"], input="\n")
        assert result.exit_code == 1

    @patch("appxen_cli.version_check.is_update_available", return_value=(False, None))
    def test_valid_key_saves(self, mock_update, monkeypatch, tmp_path):
        """Login with valid key saves config."""
        import appxen_cli.config as cfg
        config_dir = tmp_path / "config"
        config_file = config_dir / "config.toml"
        monkeypatch.setattr(cfg, "CONFIG_DIR", config_dir)
        monkeypatch.setattr(cfg, "CONFIG_FILE", config_file)

        runner = CliRunner()
        result = runner.invoke(app, ["login"], input="axgw_test_key_123\n")
        assert result.exit_code == 0
        assert "Saved" in result.output
        assert config_file.exists()

    def test_no_orchestrator_url_option(self):
        """Login no longer has --orchestrator-url option."""
        runner = CliRunner()
        result = runner.invoke(app, ["login", "--orchestrator-url", "http://x"], input="axgw_test\n")
        assert result.exit_code != 0
        assert "No such option" in result.output or "no such option" in result.output.lower()

    def test_no_tenant_id_option(self):
        """Login no longer has --tenant-id option."""
        runner = CliRunner()
        result = runner.invoke(app, ["login", "--tenant-id", "t1"], input="axgw_test\n")
        assert result.exit_code != 0
        assert "No such option" in result.output or "no such option" in result.output.lower()
