"""The Resend provider behind `MAIL_PROVIDER=resend`: one HTTPS POST per message, stdlib only.

Sources of truth: this module, `app/services/mail.py` (the seam and the selection),
`app/config.py` (`RESEND_API_KEY`, `MAIL_FROM`), `docs/ACCOUNTS.md`. Inert until the two
lines exist: with either missing or a placeholder the seam reports `configured()` false and the
directory refuses before writing. The recipient is always the address stored on the account;
the key rides only in the Authorization header; nothing about a message is logged beyond the
provider's status. An explicit User-Agent names the app, as the collectors do.
"""

from __future__ import annotations

import json
import logging
import urllib.error
import urllib.request

from app.config import settings

log = logging.getLogger(__name__)

ENDPOINT = "https://api.resend.com/emails"
USER_AGENT = "DutyFreeProfessor-mail/1.0"
TIMEOUT_SECONDS = 15


class MailSendError(RuntimeError):
    """The provider refused or was unreachable; the caller's transaction is already committed."""


def _post(url: str, headers: dict, body: bytes) -> tuple[int, str]:
    """The one transport call; tests replace it."""
    request = urllib.request.Request(url, data=body, headers=headers, method="POST")
    with urllib.request.urlopen(request, timeout=TIMEOUT_SECONDS) as response:
        return response.status, response.read().decode("utf-8", "replace")


class ResendMailer:
    def send(self, to: str, subject: str, text: str) -> None:
        if not settings.mail_ready:
            from app.services.mail import MailNotConfigured

            raise MailNotConfigured("MAIL_PROVIDER is resend but RESEND_API_KEY or MAIL_FROM is not set.")
        payload = json.dumps({"from": settings.mail_from, "to": [to], "subject": subject, "text": text}).encode()
        headers = {
            "Authorization": f"Bearer {settings.resend_api_key}",
            "Content-Type": "application/json",
            "User-Agent": USER_AGENT,
        }
        try:
            status, _ = _post(ENDPOINT, headers, payload)
        except urllib.error.HTTPError as exc:
            log.warning("resend refused a message: HTTP %s", exc.code)
            raise MailSendError(f"The mail provider answered HTTP {exc.code}.") from None
        except (urllib.error.URLError, TimeoutError, OSError) as exc:
            log.warning("resend unreachable: %s", exc.__class__.__name__)
            raise MailSendError("The mail provider could not be reached.") from None
        if status >= 300:
            raise MailSendError(f"The mail provider answered HTTP {status}.")
