"""Tests for configuration file loading."""

from pathlib import Path

import pytest

from azure_discovery.adt_types import AzureDiscoveryRequest, AzureEnvironment
from azure_discovery.utils.config_files import (
    deep_merge,
    load_config_file,
    load_request_from_file,
)


class TestDeepMerge:
    """Tests for deep_merge."""

    def test_shallow_override(self) -> None:
        merged = deep_merge({"a": 1, "b": 2}, {"b": 3})
        assert merged == {"a": 1, "b": 3}

    def test_nested_merge(self) -> None:
        merged = deep_merge(
            {"a": {"x": 1, "y": 2}, "b": 0},
            {"a": {"y": 3}},
        )
        assert merged == {"a": {"x": 1, "y": 3}, "b": 0}

    def test_override_replaces_non_dict(self) -> None:
        merged = deep_merge({"a": {"x": 1}}, {"a": 99})
        assert merged == {"a": 99}


class TestLoadJson:
    """Tests for JSON config loading."""

    def test_load_valid_json(self, tmp_path: Path) -> None:
        path = tmp_path / "config.json"
        path.write_text('{"tenant_id": "t1", "environment": "azure_public"}', encoding="utf-8")
        data = load_config_file(path)
        assert data["tenant_id"] == "t1"
        assert data["environment"] == "azure_public"

    def test_load_empty_json_object(self, tmp_path: Path) -> None:
        path = tmp_path / "empty.json"
        path.write_text("{}", encoding="utf-8")
        data = load_config_file(path)
        assert data == {}

    def test_load_json_array_raises(self, tmp_path: Path) -> None:
        path = tmp_path / "array.json"
        path.write_text("[]", encoding="utf-8")
        with pytest.raises(ValueError, match="object at the top level"):
            load_config_file(path)


class TestLoadToml:
    """Tests for TOML config loading."""

    def test_load_valid_toml(self, tmp_path: Path) -> None:
        path = tmp_path / "config.toml"
        path.write_text('tenant_id = "t1"\nenvironment = "azure_public"', encoding="utf-8")
        data = load_config_file(path)
        assert data["tenant_id"] == "t1"
        assert data["environment"] == "azure_public"

    def test_load_empty_toml(self, tmp_path: Path) -> None:
        path = tmp_path / "empty.toml"
        path.write_text("", encoding="utf-8")
        data = load_config_file(path)
        assert data == {}


class TestLoadYaml:
    """Tests for YAML config loading."""

    def test_load_valid_yaml(self, tmp_path: Path) -> None:
        path = tmp_path / "config.yaml"
        path.write_text("tenant_id: t1\nenvironment: azure_public", encoding="utf-8")
        data = load_config_file(path)
        assert data["tenant_id"] == "t1"
        assert data["environment"] == "azure_public"

    def test_load_yml_extension(self, tmp_path: Path) -> None:
        path = tmp_path / "config.yml"
        path.write_text("tenant_id: t2", encoding="utf-8")
        data = load_config_file(path)
        assert data["tenant_id"] == "t2"


class TestLoadConfigFileValidation:
    """Tests for load_config_file validation."""

    def test_unsupported_suffix_raises(self, tmp_path: Path) -> None:
        path = tmp_path / "config.txt"
        path.write_text("tenant_id = t1", encoding="utf-8")
        with pytest.raises(ValueError, match="Unsupported config format"):
            load_config_file(path)


class TestLoadRequestFromFile:
    """Tests for load_request_from_file."""

    def test_load_request_json(self, tmp_path: Path) -> None:
        path = tmp_path / "request.json"
        path.write_text(
            '{"tenant_id": "tenant-1", "environment": "azure_public"}',
            encoding="utf-8",
        )
        req = load_request_from_file(path)
        assert isinstance(req, AzureDiscoveryRequest)
        assert req.tenant_id == "tenant-1"
        assert req.environment == AzureEnvironment.AZURE_PUBLIC

    def test_load_request_toml(self, tmp_path: Path) -> None:
        path = tmp_path / "request.toml"
        path.write_text(
            'tenant_id = "tenant-2"\nenvironment = "azure_gov"',
            encoding="utf-8",
        )
        req = load_request_from_file(path)
        assert req.tenant_id == "tenant-2"
        assert req.environment == AzureEnvironment.AZURE_GOV

    def test_load_request_yaml(self, tmp_path: Path) -> None:
        path = tmp_path / "request.yaml"
        path.write_text(
            "tenant_id: tenant-3\nenvironment: azure_china",
            encoding="utf-8",
        )
        req = load_request_from_file(path)
        assert req.tenant_id == "tenant-3"
        assert req.environment == AzureEnvironment.AZURE_CHINA

    def test_load_request_strips_tenant_id_whitespace(self, tmp_path: Path) -> None:
        """Config-loaded request strips leading/trailing whitespace from tenant_id."""
        path = tmp_path / "request.json"
        path.write_text(
            '{"tenant_id": "  my-tenant-from-file  ", "environment": "azure_public"}',
            encoding="utf-8",
        )
        req = load_request_from_file(path)
        assert req.tenant_id == "my-tenant-from-file"
