"""Tests for plan gating enforcement."""

from __future__ import annotations


from qremotex.plan_gating import (
    PlanGatingError,
    REJECTION_EXECUTOR_LIMIT,
    REJECTION_KEY_EXPIRED,
    REJECTION_KEY_REVOKED,
    REJECTION_PLAN_NOT_ALLOWED,
    check_entitlements,
    handle_gateway_rejection,
    is_permanent_rejection,
)


class TestHandleGatewayRejection:
    def test_plan_not_allowed(self):
        err = handle_gateway_rejection(4001, "Your plan does not support executors")
        assert err is not None
        assert err.code == REJECTION_PLAN_NOT_ALLOWED
        assert "Pro or Enterprise" in err.message or "executors" in err.message.lower()

    def test_executor_limit(self):
        err = handle_gateway_rejection(4002, "Max 5 executors reached")
        assert err is not None
        assert err.code == REJECTION_EXECUTOR_LIMIT

    def test_key_revoked(self):
        err = handle_gateway_rejection(4003, "")
        assert err is not None
        assert err.code == REJECTION_KEY_REVOKED

    def test_key_expired(self):
        err = handle_gateway_rejection(4004, "")
        assert err is not None
        assert err.code == REJECTION_KEY_EXPIRED

    def test_normal_close(self):
        err = handle_gateway_rejection(1000, "Normal closure")
        assert err is None

    def test_none_close_code(self):
        err = handle_gateway_rejection(None, "")
        assert err is None

    def test_unknown_code(self):
        err = handle_gateway_rejection(4999, "Unknown")
        assert err is None

    def test_default_message_when_reason_empty(self):
        err = handle_gateway_rejection(4001, "")
        assert err is not None
        assert "Pro or Enterprise" in err.message


class TestIsPermanentRejection:
    def test_plan_not_allowed_is_permanent(self):
        err = PlanGatingError(REJECTION_PLAN_NOT_ALLOWED, "msg")
        assert is_permanent_rejection(err) is True

    def test_key_revoked_is_permanent(self):
        err = PlanGatingError(REJECTION_KEY_REVOKED, "msg")
        assert is_permanent_rejection(err) is True

    def test_executor_limit_is_not_permanent(self):
        err = PlanGatingError(REJECTION_EXECUTOR_LIMIT, "msg")
        assert is_permanent_rejection(err) is False

    def test_key_expired_is_not_permanent(self):
        err = PlanGatingError(REJECTION_KEY_EXPIRED, "msg")
        assert is_permanent_rejection(err) is False


class TestCheckEntitlements:
    def test_empty_entitlements(self):
        warnings = check_entitlements({})
        assert warnings == []

    def test_with_entitlements(self):
        warnings = check_entitlements({
            "max_file_transfer_mb": 100,
            "mtls_allowed": True,
            "ip_allowlist_allowed": True,
            "log_retention_days": 30,
        })
        assert warnings == []
