from django.conf import settings
from django.core.mail import send_mail
from twilio.rest import Client


def send_otp_email(user, code):
    send_mail(
        subject='Your Chiez Stores verification code',
        message=(
            f'Hi {user.first_name or user.username},\n\n'
            f'Your verification code is: {code}\n\n'
            f'This code expires in 10 minutes. Do not share it with anyone.\n\n'
            f'— Chiez Stores'
        ),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[user.email],
        fail_silently=False,
    )


def send_otp_whatsapp(phone_number, code):
    client = Client(settings.TWILIO_ACCOUNT_SID, settings.TWILIO_AUTH_TOKEN)
    client.messages.create(
        from_=settings.TWILIO_WHATSAPP_FROM,
        to=f'whatsapp:{phone_number}',
        body=(
            f'Your Chiez Stores verification code is: *{code}*\n'
            f'This code expires in 10 minutes. Do not share it.'
        ),
    )


def send_otp(user, profile, code):
    if profile.method == 'whatsapp':
        send_otp_whatsapp(profile.phone_number, code)
    else:
        send_otp_email(user, code)
        
def send_welcome_email(user):
    send_mail(
        subject='Welcome to Chiez Stores 🎉',
        message=(
            f'Hi {user.first_name or user.username},\n\n'
            f'Welcome to Chiez Stores! Your account has been created successfully.\n\n'
            f'You can now shop our exclusive collection and track your orders.\n\n'
            f'If you have any questions, feel free to reach out to us.\n\n'
            f'— The Chiez Stores Team'
        ),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[user.email],
        fail_silently=False,
    )


def send_login_notification_email(user):
    from django.utils import timezone
    now = timezone.now().strftime('%B %d, %Y at %I:%M %p')
    send_mail(
        subject='New Login to Your Chiez Stores Account',
        message=(
            f'Hi {user.first_name or user.username},\n\n'
            f'We noticed a new login to your account on {now}.\n\n'
            f'If this was you, no action is needed.\n\n'
            f'If you did not log in, please change your password immediately '
            f'or contact our support team.\n\n'
            f'— The Chiez Stores Team'
        ),
        from_email=settings.DEFAULT_FROM_EMAIL,
        recipient_list=[user.email],
        fail_silently=False,
    )
    
