from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.conf import settings
from django.template.loader import render_to_string
from alumni.models import Alumni, Job

import requests

class Command(BaseCommand):
    help = "Send email and SMS notification to all alumni about NEW job postings only"

    def handle(self, *args, **kwargs):
        # Only get new jobs that haven't been notified yet
        new_jobs = Job.objects.filter(is_active=True, is_notified=False)
        if not new_jobs.exists():
            self.stdout.write("No new job postings to notify.")
            return

        alumni_list = Alumni.objects.filter(user__is_active=True)
        if not alumni_list.exists():
            self.stdout.write("No alumni found to notify.")
            return

        # --- EMAIL NOTIFICATION ---
        for alumni in alumni_list:
            if alumni.user.email:
                subject = "New Job Opportunities for Alumni"
                message = render_to_string("alumni/active_jobs_notification.html", {
                    "alumni": alumni,
                    "job_summary": new_jobs
                })
                send_mail(
                    subject,
                    "New jobs available!",  # fallback plain text
                    settings.DEFAULT_FROM_EMAIL,
                    [alumni.user.email],
                    html_message=message,
                    fail_silently=False
                )
                self.stdout.write(f"Email sent to {alumni.user.email}")

        # --- SMS NOTIFICATION ---
        sms_api_key = settings.MNOTIFY_API_KEY
        sms_endpoint = 'https://api.mnotify.com/api/sms/quick'

        for alumni in alumni_list:
            if alumni.contact_number:
                data = {
                    "recipient": [alumni.contact_number],
                    "sender": settings.MNOTIFY_SENDER_ID,
                    "message": f"Hello {alumni.full_name}, new job postings available! Check your alumni portal.",
                    "is_schedule": False,
                    "schedule_date": ""
                }
                response = requests.post(f"{sms_endpoint}?key={sms_api_key}", json=data)
                if response.status_code == 200:
                    self.stdout.write(f"SMS sent to {alumni.contact_number}")
                else:
                    self.stdout.write(f"Failed to send SMS to {alumni.contact_number}: {response.text}")

        # Mark these jobs as notified
        new_jobs.update(is_notified=True)

        self.stdout.write(self.style.SUCCESS("New job notifications sent successfully."))