# account/utils.py
import logging
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.html import strip_tags
from django.conf import settings
import random

# Configure the logger
logger = logging.getLogger(__name__)

def generate_otp(length=6):
    otp_chars = "0123456789" 
    otp = ''.join(random.choice(otp_chars) for _ in range(length))
    return otp


def send_otp_email(user,otp):
    """Send OTP to the user's email."""
    otp = otp
    subject = "کد تائید حساب آسان باور شما."

    # Define the context for the email template
    context = {
        "user": user,
        "otp": otp,
        "support_email": "info@asanbawar.com",
        "homepage_link": "http://127.0.0.1:0000",
        "logo_url": "http://127.0.0.1:8000/media/images/logo.png",
    }

    # Render the HTML message using a template
    html_message = render_to_string("otp_email.html", context)
    
    # Create a plain text version by stripping HTML tags
    plain_message = strip_tags(html_message)
    
    # Get the sender's email from settings
    from_email = settings.EMAIL_HOST_USER
    to_email = user.email

    try:
        # Send the email
        send_mail(
            subject,
            plain_message,
            from_email,
            [to_email],
            html_message=html_message,
            fail_silently=False,  # Ensure exceptions are raised on failure
        )
        logger.info(f"OTP email sent to {to_email}")
    except Exception as e:
        logger.error(f"Error sending OTP email to {to_email}: {e}")
        # Optionally, you can re-raise the exception if you want to handle it further up the call stack
        raise e

    # Store the OTP in the user instance for future verification
    user.email_otp = otp
    user.save()




logger = logging.getLogger(__name__)


def send_forgot_password_email(user, reset_link):
    subject = "Password Reset Request"
    context = {
        "user": user,
        "reset_link": reset_link,
        "support_email": "info@asanbawar.com",
        "homepage_link": "http://127.0.0.1:0000",
        "logo_url": "http://127.0.0.1:8000/media/images/logo.png",
    }
    html_message = render_to_string("forgot_password_email.html", context)
    plain_message = strip_tags(html_message)
    from_email = settings.EMAIL_HOST_USER
    to_email = user.email

    try:
        send_mail(
            subject, plain_message, from_email, [to_email], html_message=html_message
        )
        logger.info(f"Password reset email sent to {to_email}")
    except Exception as e:
        logger.error(f"Error sending email to {to_email}: {e}")