from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from pydantic import EmailStr
import os
from dotenv import load_dotenv

conf = ConnectionConfig(
    MAIL_USERNAME=os.getenv("MAIL_USERNAME"),
    MAIL_PASSWORD=os.getenv("MAIL_PASSWORD"),
    MAIL_FROM=os.getenv("MAIL_FROM"),
    MAIL_PORT=int(os.getenv("MAIL_PORT")),
    MAIL_SERVER=os.getenv("MAIL_SERVER"),
    MAIL_STARTTLS=os.getenv("MAIL_STARTTLS") == "True",
    MAIL_SSL_TLS=os.getenv("MAIL_SSL_TLS") == "True",
    USE_CREDENTIALS=os.getenv("USE_CREDENTIALS") == "True",
)


async def send_mail(email: EmailStr, code: str):
  
    # HTML du mail
    template = f"""
    <!DOCTYPE html>
    <html lang="fr">
    <head>
      <meta charset="UTF-8" />
      <title>Validation de compte TIM CASH</title>
    </head>
    <body style="background-color: #f4f4f4; padding: 20px; font-family: Arial, sans-serif;">
      <div style="max-width: 600px; margin: auto; background: white; padding: 30px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
        
        <h2 style="text-align: center; color: #4caf50;">👋 Bonjour !</h2>
        <p>Merci d'utiliser notre service TIM CASH. Voici votre code de vérification :</p>
        
        <div style="background-color: #f0f0f0; padding: 15px; font-size: 24px; font-weight: bold; text-align: center; border-radius: 5px; margin: 20px 0; letter-spacing: 2px;">
          {code}
        </div>
        
        <p>Ce code est valable pour une durée limitée. Ne le partagez avec personne.</p>
        
        <div style="text-align: center; margin-top: 40px;">
          <img src="https://yourdomain.com/logo.png" alt="Logo TIM CASH" style="width: 120px; height: auto;" />
        </div>
        
        <div style="font-size: 12px; color: #888; text-align: center; margin-top: 20px;">
          &copy; 2025 TIM CASH. Tous droits réservés.
        </div>
      </div>
    </body>
    </html>
    """

    message = MessageSchema(
        subject="Validation de compte TIM CASH",
        recipients=[email],
        body=template,
        subtype="html"
    )

    fm = FastMail(conf)
    try:
        await fm.send_message(message)
        print(f"✅ Mail envoyé à {email}")
    except Exception as e:
        print(f"❌ Erreur lors de l'envoi du mail: {e}")
