"""Schema Guard 单元测试"""

from __future__ import annotations

import pytest

from packages.adapters.sqlalchemy_impl.schema_guard import (
    BLOCKED_AUTO_CREATE_ENVIRONMENTS,
    assert_auto_create_schema_allowed,
    normalize_environment,
)


class TestNormalizeEnvironment:
    """normalize_environment 测试"""

    def test_development(self):
        assert normalize_environment("development") == "development"

    def test_staging(self):
        assert normalize_environment("staging") == "staging"

    def test_production(self):
        assert normalize_environment("production") == "production"

    def test_none_returns_development(self):
        assert normalize_environment(None) == "development"

    def test_empty_string_returns_development(self):
        assert normalize_environment("") == "development"

    def test_case_insensitive(self):
        assert normalize_environment("PRODUCTION") == "production"
        assert normalize_environment("Staging") == "staging"

    def test_strips_whitespace(self):
        assert normalize_environment("  production  ") == "production"


class TestAssertAutoCreateSchemaAllowed:
    """assert_auto_create_schema_allowed 测试"""

    def test_development_enabled_ok(self):
        # development 环境允许 auto_create
        assert_auto_create_schema_allowed("development", True)

    def test_development_disabled_ok(self):
        assert_auto_create_schema_allowed("development", False)

    def test_staging_disabled_ok(self):
        # staging 禁用时没问题
        assert_auto_create_schema_allowed("staging", False)

    def test_production_disabled_ok(self):
        assert_auto_create_schema_allowed("production", False)

    def test_staging_enabled_raises(self):
        with pytest.raises(RuntimeError, match="AUTO_CREATE_SCHEMA"):
            assert_auto_create_schema_allowed("staging", True)

    def test_production_enabled_raises(self):
        with pytest.raises(RuntimeError, match="AUTO_CREATE_SCHEMA"):
            assert_auto_create_schema_allowed("production", True)

    def test_case_insensitive_blocked(self):
        with pytest.raises(RuntimeError):
            assert_auto_create_schema_allowed("PRODUCTION", True)
        with pytest.raises(RuntimeError):
            assert_auto_create_schema_allowed("Staging", True)

    def test_none_environment_enabled_ok(self):
        # None 视为 development，允许
        assert_auto_create_schema_allowed(None, True)

    def test_custom_env_enabled_ok(self):
        # 其他环境不受限制
        assert_auto_create_schema_allowed("test", True)
        assert_auto_create_schema_allowed("qa", True)

    def test_blocked_environments_count(self):
        # 确认只有 staging 和 production 被阻止
        assert "staging" in BLOCKED_AUTO_CREATE_ENVIRONMENTS
        assert "production" in BLOCKED_AUTO_CREATE_ENVIRONMENTS
        assert len(BLOCKED_AUTO_CREATE_ENVIRONMENTS) == 2
