from email.message import EmailMessage
from secrets import token_hex
from smtplib import SMTP_SSL
from typing import Tuple

from constants import DOMAIN, PASSWORD, USERNAME
from database.crud import save_attribute


def initialize_smtp(domain, username, password) -> SMTP_SSL:
    """
    Creates the SMTP connection to the mail server
    """
    server = SMTP_SSL(domain)
    server.login(username, password)
    return server


def format_message(sender, recipient) -> Tuple[EmailMessage, str]:
    """
    Creates the email message and formats it accordingly
    """
    code = token_hex(4)
    body = f"La clave es {code}. EnvĂ­ele esta clave al bot."
    message = EmailMessage()
    message["From"] = sender
    message["To"] = recipient
    message["Subject"] = "Clave para verificar su identidad"
    message.set_content(body)
    return message, code


def send_mail(recipient) -> None:
    """
    Sends an email to the specified recipient
    """
    server = initialize_smtp(domain=DOMAIN, username=USERNAME, password=PASSWORD)
    message, code = format_message(sender=USERNAME, recipient=recipient)
    save_attribute(id=recipient, attribute="codigo", data=code)
    server.send_message(msg=message)
    server.close()