"""Generic email service for the application."""

from __future__ import annotations

import logging
from typing import Sequence

from django.conf import settings
from django.core.mail import send_mail
from django.template.loader import render_to_string

logger = logging.getLogger(__name__)


class EmailService:
    """Generic email sender.

    Usage:
        EmailService.send(
            to="user@example.com",
            subject="Payment Received",
            template="emails/payment_success.txt",
            context={"name": "Ahmed", "amount": "100 AED"},
        )

        # Or with a plain message (no template):
        EmailService.send(
            to=["user@example.com"],
            subject="Hello",
            message="Plain text body",
        )
    """

    @classmethod
    def send(
        cls,
        *,
        to: str | Sequence[str],
        subject: str,
        message: str = "",
        template: str | None = None,
        context: dict | None = None,
        from_email: str | None = None,
        fail_silently: bool = False,
    ) -> bool:
        """Send an email.

        Args:
            to: Recipient email address or list of addresses.
            subject: Email subject line.
            message: Plain text body (used if template is not provided).
            template: Optional path to a Django text template (e.g. "emails/payment.txt").
            context: Template context dict (used only with template).
            from_email: Sender address (defaults to DEFAULT_FROM_EMAIL).
            fail_silently: If True, suppress exceptions on send failure.

        Returns:
            True if the email was sent successfully, False otherwise.
        """
        if isinstance(to, str):
            recipient_list = [to]
        else:
            recipient_list = list(to)

        if not recipient_list:
            logger.warning("EmailService.send called with empty recipient list")
            return False

        if template:
            body = render_to_string(template, context or {})
        else:
            body = message

        sender = from_email or settings.DEFAULT_FROM_EMAIL

        try:
            send_mail(
                subject=subject,
                message=body,
                from_email=sender,
                recipient_list=recipient_list,
                fail_silently=fail_silently,
            )
            logger.info("Email sent to %s: %s", recipient_list, subject)
            return True
        except Exception:
            logger.exception("Failed to send email to %s: %s", recipient_list, subject)
            if not fail_silently:
                raise
            return False
