"""Email service for sending support emails via Mailgun."""
import httpx
from app.config import settings


class EmailService:
    """Service for sending emails via Mailgun API."""

    async def send_support_email(
        self,
        message: str,
        subject: str,
        user_name: str | None = None,
        user_email: str | None = None,
    ) -> bool:
        """Send a support email via Mailgun API.

        Args:
            message: The message body
            subject: Email subject line
            user_name: Optional name of the user submitting
            user_email: Optional email of the user submitting

        Returns:
            True if email was sent successfully, False otherwise
        """
        # Validate Mailgun configuration
        if not settings.MAILGUN_API_URL or not settings.MAILGUN_API_URL.startswith(
            ("http://", "https://")
        ):
            print("Warning: MAILGUN_API_URL not configured or missing protocol")
            return False

        if not settings.MAILGUN_API_KEY:
            print("Warning: MAILGUN_API_KEY not configured")
            return False

        body = f"From: {user_name or 'Anonymous'}\nEmail: {user_email or 'Not provided'}\n\n{message}"

        async with httpx.AsyncClient() as client:
            response = await client.post(
                settings.MAILGUN_API_URL,
                auth=("api", settings.MAILGUN_API_KEY),
                data={
                    "from": settings.MAILGUN_FROM,
                    "to": settings.SUPPORT_EMAIL,
                    "subject": subject,
                    "text": body,
                },
            )
            return response.status_code == 200


email_service = EmailService()
