from celery import shared_task
from django.core.mail import EmailMultiAlternatives
from django.template.loader import render_to_string
from .models import EndUser,Watchers,Shoots
from django.utils.timezone import now

@shared_task
def send_comment_notification_email(client_email, job_number, comment_text, comment_image):
    # Get product sample by job number
    product_sample = ProductSample.objects.filter(job_number=job_number).first()
    if not product_sample:
        return  # No product found, exit task

    product_id = product_sample.id

    # Get admin users with verified emails
    admin_users = EndUser.objects.filter(is_admin=True, email_verified=True)

    # Get watchers related to the product
    watchers = Watchers.objects.filter(product_id=product_id).select_related('user')

    # Get shoot users related to the product
    shoots = Shoots.objects.filter(product_id=product_id).select_related('user')

    # Collect all relevant users' emails
    email_user_map = {}

    # Admin users
    for user in admin_users:
        email_user_map[user.email] = user.name

    # Watchers
    for watcher in watchers:
        user = watcher.user
        if user.email_verified:
            email_user_map[user.email] = user.name

    # Shoots
    for shoot in shoots:
        user = shoot.user
        if user.email_verified:
            email_user_map[user.email] = user.name

    # Send email to each unique user
    for email, name in email_user_map.items():
        subject = f"New Comment on Job #{job_number} – Lionshead Studios"
        from_email = 'ambt.reporting@gmail.com'
        to_email = email

        html_content = render_to_string(
            "product_comment_update.html",
            {
                'user_name': name,
                'client_name': client_email,
                'job_number': job_number,
                'comment_text': comment_text,
                'comment_image': comment_image,
                'current_year': now().year,
                'url': f"https://lionshead.tidera.ai/admin/products/{product_sample.tm_article_number}"
            }
        )

        msg = EmailMultiAlternatives(subject, "", from_email, [to_email])
        msg.attach_alternative(html_content, "text/html")
        msg.send()