from flask import Flask, request, jsonify
from app.routes.smtp import read_smtp
from app.database.database import SessionLocal
from fastapi_mail import FastMail, MessageSchema, ConnectionConfig
from threading import Thread

from flask import  request, jsonify, Blueprint
from werkzeug.utils import secure_filename  # Utilisé pour sécuriser le nom du fichier

router = Blueprint('envoi', __name__)

# Get SMTP configuration
def get_db():
    db = SessionLocal()
    try:
        yield db
    finally:
        db.close()

infos = read_smtp()
conf = ConnectionConfig(
    MAIL_USERNAME=infos[0].get('username'),
    MAIL_PASSWORD=infos[0].get('password'),
    MAIL_FROM=infos[0].get('sender_email_address'),
    MAIL_PORT=infos[0].get('port'),
    MAIL_SERVER=infos[0].get('hostname'),
    MAIL_STARTTLS=True,
    MAIL_SSL_TLS=False,
    USE_CREDENTIALS=True
)
print (conf)
# def send_email_task(email_data):
#     m = 'support_rh@finashore.ma'
#     message = MessageSchema(
#         subject=email_data['subject'],
#         recipients=[email_data['email']],
#         cc=[m],
#         body=email_data['body'],
#         subtype="html"
#     )

#     fm = FastMail(conf)
#     import asyncio
#     loop = asyncio.new_event_loop()
#     asyncio.set_event_loop(loop)
#     loop.run_until_complete(fm.send_message(message))
#     loop.close()
def send_email_task(email_data):
    m = 'support_rh@finashore.ma'
    message = MessageSchema(
        subject=email_data['subject'],
        recipients=[email_data['email']],
        cc=[m],
        body=email_data['body'],
        subtype="html"
    )

    fm = FastMail(conf)
    try:
        import asyncio
        loop = asyncio.new_event_loop()
        asyncio.set_event_loop(loop)
        loop.run_until_complete(fm.send_message(message))
    except Exception as e:
        print("Erreur lors de l'envoi de l'email:", e)
    finally:
        loop.close()

# @router.route('/send-email/', methods=['POST'])
# def send_email():
#     email_data = request.get_json()

#     if not all(k in email_data for k in ('email', 'subject', 'body')):
#         return jsonify({'error': 'Missing fields'}), 400

#     thread = Thread(target=send_email_task, args=(email_data,))
#     thread.start()

#     return jsonify({"message": "Email envoyé avec succès"}), 200
@router.route('/send-email/', methods=['POST'] )
def send_email():
    email_data = request.get_json()

    if not all(k in email_data for k in ('email', 'subject', 'body')):
        return jsonify({'error': 'Missing fields'}), 400

    try:
        send_email_task(email_data)
        return jsonify({"message": "Email envoyé avec succès"}), 200
    except Exception as e:
        print("Erreur lors de l'envoi de l'e-mail:", e)
        return jsonify({"error": "Échec de l'envoi de l'e-mail"}), 500

# if __name__ == '__main__':
#     run(debug=True)
