import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

from core.environment import Environment
from core.logger import MailLogger

logger = MailLogger("MailService")


class MailService:

    def __init__(self):
        self._server = Environment.get("MAIL_SERVER", str)
        self._port = Environment.get("MAIL_PORT", int)
        self._user = Environment.get("MAIL_USER", str)
        self._password = Environment.get("MAIL_PASSWORD", str)
        self._from = Environment.get("MAIL_FROM", str)

        if not all([self._server, self._port, self._user, self._password, self._from]):
            raise ValueError("Mail server configuration is incomplete.")

    def send(self, to: str, subject: str, body: str):
        logger.debug(f"Preparing to send email to: {to}, subject: {subject}")

        msg = MIMEMultipart()
        msg["From"] = self._from
        msg["To"] = to
        msg["Subject"] = subject

        msg.attach(MIMEText(body, "plain"))

        try:
            logger.info(f"Connecting to mail server: {self._server}:{self._port}")
            with smtplib.SMTP(self._server, self._port) as server:
                server.starttls()
                logger.debug("Starting TLS encryption")
                server.login(self._user, self._password)
                logger.info(f"Logged in as: {self._user}")
                server.sendmail(self._from, to, msg.as_string())
                logger.info(f"Email successfully sent to: {to}")
        except Exception as e:
            logger.error(f"Failed to send email to {to}", e)


mailService = MailService()
