"""Unit tests for SendGridEmailBackend — no Postgres needed."""
import pytest


class _FakeMail:
    def __init__(self, **kw):
        self._kw = kw
        self.reply_to = None


class _FakeReplyTo:
    def __init__(self, addr):
        self.addr = addr


class _FakeResponseOK:
    status_code = 202
    body = b""


class _FakeResponse400:
    status_code = 400
    body = b"bad request"


class _FakeClient:
    def __init__(self, resp):
        self._resp = resp

    def send(self, msg):
        self.last_msg = msg
        return self._resp


def _patch_sendgrid(monkeypatch, resp):
    fake_client = _FakeClient(resp)
    monkeypatch.setattr(
        "app.services.email.SendGridAPIClient",
        lambda _key: fake_client,
    )
    monkeypatch.setattr("app.services.email.Mail", _FakeMail)
    monkeypatch.setattr("app.services.email.ReplyTo", _FakeReplyTo)
    return fake_client


def test_sendgrid_send_calls_api(monkeypatch):
    client = _patch_sendgrid(monkeypatch, _FakeResponseOK())

    from app.services.email import SendGridEmailBackend
    backend = SendGridEmailBackend()
    backend.send(to="to@example.com", subject="Hello", html="<p>Hi</p>")

    assert hasattr(client, "last_msg")


def test_sendgrid_raises_on_4xx(monkeypatch):
    _patch_sendgrid(monkeypatch, _FakeResponse400())

    from app.services.email import SendGridEmailBackend
    backend = SendGridEmailBackend()
    with pytest.raises(RuntimeError, match="400"):
        backend.send(to="to@example.com", subject="Hello", html="<p>Hi</p>")
