import os
from unittest import mock

import importlib


def test_service_principal_credential(tmp_path, monkeypatch):
    # ensure env vars are set for service principal
    monkeypatch.setenv("AZURE_CLIENT_ID", "cid")
    monkeypatch.setenv("AZURE_CLIENT_SECRET", "csecret")
    monkeypatch.setenv("AZURE_TENANT_ID", "ctenant")
    monkeypatch.setenv("AZURE_SUBSCRIPTION_ID", "subid")

    # create a fake azure.identity module with ClientSecretCredential
    fake_module = mock.MagicMock()

    class FakeCred:
        def __init__(self, tenant_id=None, client_id=None, client_secret=None):
            self.tenant_id = tenant_id
            self.client_id = client_id
            self.client_secret = client_secret

    fake_module.ClientSecretCredential = FakeCred

    with mock.patch.dict("sys.modules", {"azure.identity": fake_module}):
        # reload the module under test to pick up the patched azure.identity
        mod = importlib.import_module("py_azpe.azure_auth")
        importlib.reload(mod)
        cred = mod.get_credential()
        assert isinstance(cred, FakeCred)
        assert cred.client_id == "cid"
        assert cred.client_secret == "csecret"
        assert cred.tenant_id == "ctenant"


def test_default_credential_fallback(monkeypatch):
    # ensure service principal env vars are not set
    monkeypatch.delenv("AZURE_CLIENT_ID", raising=False)
    monkeypatch.delenv("AZURE_CLIENT_SECRET", raising=False)
    monkeypatch.delenv("AZURE_TENANT_ID", raising=False)
    monkeypatch.setenv("AZURE_SUBSCRIPTION_ID", "subid")

    fake_module = mock.MagicMock()

    class FakeDefault:
        def __init__(self):
            pass

    fake_module.DefaultAzureCredential = FakeDefault

    with mock.patch.dict("sys.modules", {"azure.identity": fake_module}):
        mod = importlib.import_module("py_azpe.azure_auth")
        importlib.reload(mod)
        cred = mod.get_credential()
        assert isinstance(cred, FakeDefault)


# end of test_azure_auth.py
