from __future__ import annotations

import smtplib
from email.message import EmailMessage

from .config import Config


def _send_message(config: Config, message: EmailMessage) -> None:
    smtp_class = smtplib.SMTP_SSL if config.smtp_ssl else smtplib.SMTP
    with smtp_class(config.smtp_host, config.smtp_port, timeout=20) as smtp:
        if config.smtp_starttls and not config.smtp_ssl:
            smtp.starttls()
        if config.smtp_username:
            smtp.login(config.smtp_username, config.smtp_password)
        smtp.send_message(message)


def send_verification_email(config: Config, to_email: str, verify_url: str) -> None:
    message = EmailMessage()
    message["From"] = config.smtp_from
    message["To"] = to_email
    message["Subject"] = "Verify your Sticknife account"
    message.set_content(
        "\n".join(
            [
                "Welcome to Sticknife.",
                "",
                "Verify your email address to continue:",
                verify_url,
                "",
                "If you did not request this, you can ignore this email.",
            ]
        )
    )

    _send_message(config, message)



def send_password_reset_email(config: Config, to_email: str, reset_url: str) -> None:
    message = EmailMessage()
    message["From"] = config.smtp_from
    message["To"] = to_email
    message["Subject"] = "Set your Sticknife password"
    message.set_content(
        "\n".join(
            [
                "Your Sticknife account is ready.",
                "",
                "Set or reset your password here:",
                reset_url,
                "",
                "This link expires soon. If you did not request this, you can ignore this email.",
            ]
        )
    )
    _send_message(config, message)
