from flask import current_app, render_template
from flask_mail import Message
from app.extensions import mail
from app.services.settings_service import email_branding_context, email_cc_admin_enabled


def send_templated_email(to, subject, template, cc_admin=False, **context):
    try:
        msg = Message(subject=subject, recipients=[to])
        if cc_admin and email_cc_admin_enabled():
            admin_cc = current_app.config.get("MAIL_CC_ADMIN")
            if admin_cc:
                msg.cc = [admin_cc]
        context = {**context, "subject": subject, "brand": email_branding_context()}
        msg.html = render_template(template, **context)
        mail.send(msg)
        return True
    except Exception as exc:
        current_app.logger.warning("Email send failed: %s", exc)
        return False


def send_plain_email(to, subject, body, cc_admin=False):
    try:
        msg = Message(subject=subject, recipients=[to])
        if cc_admin:
            admin_cc = current_app.config.get("MAIL_CC_ADMIN")
            if admin_cc:
                msg.cc = [admin_cc]
        msg.body = body
        mail.send(msg)
        return True
    except Exception as exc:
        current_app.logger.warning("Email send failed: %s", exc)
        return False
