from django.core.management.base import BaseCommand
from django.db.models import Count, Q
from django.utils.timezone import now, timedelta
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.conf import settings

from alumni.models import Alumni


class Command(BaseCommand):
    help = "Send weekly reminders to alumni with incomplete profiles"

    def handle(self, *args, **kwargs):

        alumni_list = Alumni.objects.annotate(
            academic_count=Count('academic_records'),
            employment_count=Count('employment_records')
        ).filter(
            Q(academic_count=0) | Q(employment_count=0)
        ).distinct()

       
        for alumni in alumni_list:

            # EMAIL
            if alumni.user.email:
                subject = "Complete Your Alumni Profile"
                message = render_to_string("alumni/incomplete_profile_notification_email.html", {
                    "alumni": alumni,
                })
                
                send_mail(
                    subject,
                    plain_message = f"""
Dear {alumni.full_name},

Your alumni profile is incomplete.
Please update your academic and employment details.

Thank you.
""",  # fallback plain text
                    settings.DEFAULT_FROM_EMAIL,
                    # [alumni.user.email],
                    ['nagayewisdom@gmail.com'],
                    html_message=message,
                    fail_silently=False
                )
                self.stdout.write(f"Email sent to {alumni.user.email}")
            

        self.stdout.write(self.style.SUCCESS("Notifications sent successfully"))