"""Tests for the global configuration and singleton pattern."""

from __future__ import annotations

import pytest

from vault.config import (
    SecretsConfig,
    get_secrets,
    init_secrets,
    reset_secrets,
)
from vault.encryption import AESGCMEncryption, FernetEncryption
from vault.store import InMemorySecretStore


class TestSecretsConfig:
    def test_defaults(self):
        cfg = SecretsConfig(master_key="test")
        assert cfg.encryption_provider == "fernet"
        assert cfg.default_rotation_days == 90
        assert cfg.auto_rotate is False

    def test_aesgcm_provider(self):
        cfg = SecretsConfig(master_key="test", encryption_provider="aesgcm")
        assert cfg.encryption_provider == "aesgcm"


class TestInitAndGetSecrets:
    def test_get_before_init_raises(self):
        with pytest.raises(RuntimeError, match="not initialised"):
            get_secrets()

    def test_init_creates_container(self, secrets_config):
        container = init_secrets(secrets_config)
        assert container.store is not None
        assert container.encryption is not None
        assert container.rotation_policy is not None

    def test_get_returns_same_container(self, secrets_config):
        init_secrets(secrets_config)
        c1 = get_secrets()
        c2 = get_secrets()
        assert c1 is c2

    def test_default_uses_fernet(self, secrets_config):
        container = init_secrets(secrets_config)
        assert isinstance(container.encryption, FernetEncryption)

    def test_aesgcm_provider(self):
        cfg = SecretsConfig(master_key="test", encryption_provider="aesgcm")
        container = init_secrets(cfg)
        assert isinstance(container.encryption, AESGCMEncryption)

    def test_custom_store(self, secrets_config, fernet):
        custom_store = InMemorySecretStore(fernet)
        container = init_secrets(secrets_config, store=custom_store)
        assert container.store is custom_store

    def test_custom_encryption(self, secrets_config, aesgcm):
        container = init_secrets(secrets_config, encryption=aesgcm)
        assert container.encryption is aesgcm

    def test_reset_clears_state(self, secrets_config):
        init_secrets(secrets_config)
        reset_secrets()
        with pytest.raises(RuntimeError):
            get_secrets()

    def test_rotation_policy_from_config(self):
        cfg = SecretsConfig(master_key="x", default_rotation_days=30, auto_rotate=True)
        container = init_secrets(cfg)
        assert container.rotation_policy.max_age_days == 30
        assert container.rotation_policy.auto_rotate is True
