from flask_mail import Message
from app import mail
from flask import current_app, render_template
import logging

logger = logging.getLogger(__name__)

def is_email_configured():
    """Check if email settings are properly configured"""
    config = current_app.config
    return all([
        config.get('MAIL_USERNAME') != 'your_email@gmail.com',
        config.get('MAIL_PASSWORD') != 'your_email_password',
        config.get('MAIL_DEFAULT_SENDER') != 'your_email@gmail.com'
    ])

def send_email(msg):
    """Helper function to send emails with error handling"""
    if not is_email_configured():
        logger.warning("Email settings not configured. Skipping email send.")
        return False
        
    try:
        mail.send(msg)
        return True
    except Exception as e:
        logger.error(f"Failed to send email: {str(e)}")
        return False

def send_approval_notification(user):
    """Notify admins about new signup request"""
    msg = Message(
        'New Student Registration',
        sender=current_app.config['MAIL_DEFAULT_SENDER'],
        recipients=current_app.config['ADMIN_EMAILS']
    )
    msg.html = render_template(
        'email/new_signup.html',
        user=user
    )
    return send_email(msg)

def send_approval_email(user):
    """Send approval notification to student"""
    msg = Message(
        'Your Account Has Been Approved',
        sender=current_app.config['MAIL_DEFAULT_SENDER'],
        recipients=[user.email]
    )
    msg.html = render_template(
        'email/account_approved.html',
        user=user
    )
    return send_email(msg)

def send_rejection_email(user):
    """Send rejection notification to student"""
    msg = Message(
        'Regarding Your Account Application',
        sender=current_app.config['MAIL_DEFAULT_SENDER'],
        recipients=[user.email]
    )
    msg.html = render_template(
        'email/account_rejected.html',
        user=user
    )
    return send_email(msg)

def send_welcome_signup_email(user):
    """Send a welcome email to the user after signup (pending approval)."""
    msg = Message(
        'Welcome to Try English - Registration Received',
        sender=current_app.config['MAIL_DEFAULT_SENDER'],
        recipients=[user.email]
    )
    msg.html = render_template(
        'email/welcome_signup.html',
        user=user
    )
    return send_email(msg)
