import pytest
from unittest.mock import MagicMock, patch
from azure.core.exceptions import ResourceExistsError, ResourceNotFoundError
from aleph_secrets_manager.src.azure_keyvault_adaptor import (
    AzureClientFactory,
    AzureSecretsManager,
)
from aleph_secrets_manager.src.port import Secret


@pytest.fixture(scope="session")
def client():
    vault_name = "testvault"
    client = AzureClientFactory.create(vault_name)
    return client


@pytest.fixture(scope="session")
def secrets_manager(client):
    secrets_manager = AzureSecretsManager(client)

    clear_all_secrets(secrets_manager=secrets_manager)
    yield secrets_manager
    clear_all_secrets(secrets_manager=secrets_manager)


def clear_all_secrets(secrets_manager: AzureSecretsManager):
    keys = secrets_manager.list_all_secrets()
    for key in keys:
        secrets_manager.delete_secret(key)


def test_read_write_secret_success(secrets_manager):
    secret = Secret(key="test_key", value="test_value")
    secrets_manager.write_secret(secret)

    retrieved_secret = secrets_manager.read_secret(secret.key)
    assert secret.key == retrieved_secret.key
    assert secret.value == retrieved_secret.value


def test_write_secret_recover_deleted(secrets_manager):
    secret = Secret(key="test_key", value="test_value")
    secrets_manager.write_secret(secret)

    secrets_manager.delete_secret(secret.key)

    secrets_manager.write_secret(secret)

    retrieved_secret = secrets_manager.read_secret(secret.key)
    assert secret.key == retrieved_secret.key
    assert secret.value == retrieved_secret.value


def test_read_secret_not_found(secrets_manager):
    with pytest.raises(Exception):
        secrets_manager.read_secret("MISSING_SECRET")


def test_delete_secret_success(secrets_manager):
    secret = Secret(key="test_key", value="test_value")
    secrets_manager.write_secret(secret)

    secrets_manager.delete_secret(secret.key)

    with pytest.raises(Exception):
        secrets_manager.read_secret(secret.key)


def test_list_all_secrets(secrets_manager):
    secrets = [
        Secret(key="test_key_1", value="test_value_1"),
        Secret(key="test_key_2", value="test_value_2"),
    ]
    for secret in secrets:
        secrets_manager.write_secret(secret)

    retrieved_secrets = secrets_manager.list_all_secrets()
    assert retrieved_secrets == [s.key for s in secrets]


def test_read_all_secrets(secrets_manager):
    secrets = [
        Secret(key="test_key_1", value="test_value_1"),
        Secret(key="test_key_2", value="test_value_2"),
    ]
    for secret in secrets:
        secrets_manager.write_secret(secret)

    retrieved_secrets = secrets_manager.read_all_secrets()
    assert retrieved_secrets == secrets
