"""Tests for backend.billing.email_sender."""

from __future__ import annotations

from unittest.mock import AsyncMock, MagicMock, patch


class TestSendTemplateEmail:
    async def test_successful_send(self) -> None:
        from backend.billing.email_sender import send_template_email

        mock_resp = MagicMock()
        mock_resp.status_code = 200

        mock_client = AsyncMock()
        mock_client.__aenter__ = AsyncMock(return_value=mock_client)
        mock_client.__aexit__ = AsyncMock(return_value=False)
        mock_client.post = AsyncMock(return_value=mock_resp)

        with (
            patch(
                "backend.billing.email_sender._get_postmark_token",
                new_callable=AsyncMock,
                return_value="tok",
            ),
            patch(
                "backend.billing.email_sender.httpx.AsyncClient",
                return_value=mock_client,
            ),
        ):
            result = await send_template_email(
                "u@e.com", "test-template", {"key": "val"}
            )
            assert result is True

    async def test_5xx_retries_then_fails(self) -> None:
        from backend.billing.email_sender import send_template_email

        mock_resp = MagicMock()
        mock_resp.status_code = 500
        mock_resp.text = "Internal Server Error"

        mock_client = AsyncMock()
        mock_client.__aenter__ = AsyncMock(return_value=mock_client)
        mock_client.__aexit__ = AsyncMock(return_value=False)
        mock_client.post = AsyncMock(return_value=mock_resp)

        with (
            patch(
                "backend.billing.email_sender._get_postmark_token",
                new_callable=AsyncMock,
                return_value="tok",
            ),
            patch(
                "backend.billing.email_sender.httpx.AsyncClient",
                return_value=mock_client,
            ),
            patch("backend.billing.email_sender.asyncio.sleep", new_callable=AsyncMock),
        ):
            result = await send_template_email("u@e.com", "test-template", {})
            assert result is False
            assert mock_client.post.call_count == 2  # initial + 1 retry

    async def test_token_failure_returns_false(self) -> None:
        from backend.billing.email_sender import send_template_email

        with patch(
            "backend.billing.email_sender._get_postmark_token",
            new_callable=AsyncMock,
            side_effect=RuntimeError("no secret"),
        ):
            result = await send_template_email("u@e.com", "test-template", {})
            assert result is False
