"""The mail seam: `none` refuses, `resend` is inert until its two lines exist, then posts once.

The Resend provider sends one JSON POST with the stored address as the only recipient, the
key in the Authorization header alone, an explicit User-Agent, and never logs the body; a
provider error is a MailSendError, not a 500. The transport is replaced; no network.
"""

import json

import pytest

from app.config import settings
from app.services import mail, mail_resend


@pytest.fixture
def unconfigured(monkeypatch):
    monkeypatch.setattr(mail, "_override", None)
    monkeypatch.setattr(settings, "mail_provider", "none")
    monkeypatch.setattr(settings, "resend_api_key", "")
    monkeypatch.setattr(settings, "mail_from", "")


def test_none_provider_refuses_and_reports_unconfigured(unconfigured):
    assert mail.configured() is False
    with pytest.raises(mail.MailNotConfigured):
        mail.mailer().send("a@example.com", "s", "t")


def test_resend_is_inert_with_a_placeholder_or_missing_line(unconfigured, monkeypatch):
    monkeypatch.setattr(settings, "mail_provider", "resend")
    monkeypatch.setattr(settings, "resend_api_key", "REPLACE_WITH_KEY")
    monkeypatch.setattr(settings, "mail_from", "Duty Free Professor <hello@example.com>")
    assert mail.configured() is False
    with pytest.raises(mail.MailNotConfigured):
        mail.mailer().send("a@example.com", "s", "t")


def test_resend_posts_once_with_the_key_in_the_header_only(unconfigured, monkeypatch, caplog):
    monkeypatch.setattr(settings, "mail_provider", "resend")
    monkeypatch.setattr(settings, "resend_api_key", "re_test_not_a_real_key")
    monkeypatch.setattr(settings, "mail_from", "hello@example.com")
    calls = []

    def fake_post(url, headers, body):
        calls.append((url, headers, body))
        return 200, '{"id":"x"}'

    monkeypatch.setattr(mail_resend, "_post", fake_post)
    assert mail.configured() is True
    mail.mailer().send("adam@example.com", "Your account", "Set your password: https://x/welcome#tok")
    (url, headers, body), = calls
    assert url == mail_resend.ENDPOINT
    assert headers["Authorization"] == "Bearer re_test_not_a_real_key"
    assert headers["User-Agent"] == mail_resend.USER_AGENT
    sent = json.loads(body)
    assert sent["to"] == ["adam@example.com"] and sent["from"] == "hello@example.com"
    assert "welcome#tok" in sent["text"]
    assert "re_test_not_a_real_key" not in sent["text"] and "welcome#tok" not in caplog.text


def test_a_provider_error_is_a_send_error(unconfigured, monkeypatch):
    monkeypatch.setattr(settings, "mail_provider", "resend")
    monkeypatch.setattr(settings, "resend_api_key", "re_test_not_a_real_key")
    monkeypatch.setattr(settings, "mail_from", "hello@example.com")
    monkeypatch.setattr(mail_resend, "_post", lambda *a: (422, "no"))
    with pytest.raises(mail_resend.MailSendError):
        mail.mailer().send("adam@example.com", "s", "t")
