"""Tests for billing manager."""

from unittest.mock import MagicMock

import pytest

from ai_org.core.aws_client import AWSClient
from ai_org.core.billing_manager import BillingManager


@pytest.fixture
def mock_billing():
    """Create a BillingManager with mocked AWS client."""
    aws = MagicMock(spec=AWSClient)
    aws.client.return_value = MagicMock()
    return BillingManager(aws)


@pytest.mark.unit
class TestBillingManager:
    def test_init(self, mock_billing):
        assert mock_billing.table_name == "stripe-customer-mappings"
        assert mock_billing.aws_client is not None

    def test_account_id_property(self, mock_billing):
        sts_mock = MagicMock()
        sts_mock.get_caller_identity.return_value = {"Account": "123456789012"}
        mock_billing.aws_client.client.return_value = sts_mock
        assert mock_billing.account_id == "123456789012"

    def test_get_stripe_api_key_from_test_env(self, mock_billing, monkeypatch):
        monkeypatch.setenv("TEST_STRIPE_SECRET_KEY", "sk_test_123")
        key = mock_billing._get_stripe_api_key()
        assert key == "sk_test_123"

    def test_get_stripe_api_key_from_prod_env(self, mock_billing, monkeypatch):
        monkeypatch.delenv("TEST_STRIPE_SECRET_KEY", raising=False)
        monkeypatch.setenv("STRIPE_SECRET_KEY", "sk_live_456")
        from botocore.exceptions import ClientError

        mock_billing.secrets_client.get_secret_value.side_effect = ClientError(
            {"Error": {"Code": "ResourceNotFoundException", "Message": "not found"}},
            "GetSecretValue",
        )
        key = mock_billing._get_stripe_api_key()
        assert key == "sk_live_456"

    def test_get_stripe_api_key_no_key_raises(self, mock_billing, monkeypatch):
        monkeypatch.delenv("TEST_STRIPE_SECRET_KEY", raising=False)
        monkeypatch.delenv("STRIPE_SECRET_KEY", raising=False)
        from botocore.exceptions import ClientError

        mock_billing.secrets_client.get_secret_value.side_effect = ClientError(
            {"Error": {"Code": "ResourceNotFoundException", "Message": "not found"}},
            "GetSecretValue",
        )
        with pytest.raises(Exception, match="Stripe API key not found"):
            mock_billing._get_stripe_api_key()

    def test_get_stripe_api_key_from_secrets_manager(self, mock_billing, monkeypatch):
        monkeypatch.delenv("TEST_STRIPE_SECRET_KEY", raising=False)
        import json

        mock_billing.secrets_client.get_secret_value.return_value = {
            "SecretString": json.dumps({"api_key": "sk_from_sm"})
        }
        key = mock_billing._get_stripe_api_key()
        assert key == "sk_from_sm"
