from background_task import background
from users.management.commands.send_travel_insurance_expiry_email import Command
from django.core.management.base import BaseCommand
from django.core.mail import EmailMessage
from django.utils import timezone
from datetime import timedelta
from users.models import ClientTravelInsurance, EmailSetup
import logging
import os

@background(schedule=0)
def send_travel_insurance_expiry_email_task():
    log_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'insurance_report.log')
    logging.basicConfig(filename=log_file, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

    class Command(BaseCommand):
        help = "Send travel insurance expiry report emails for next week"

        def handle(self, *args, **kwargs):
            try:
                today = timezone.localdate()

                # Current Saturday
                saturday = today + timedelta((5 - today.weekday()) % 7)  # Saturday = 5

                # Next Monday
                monday = saturday + timedelta(days=(7 - saturday.weekday()))  # Monday = 0

                # Next Sunday
                sunday = monday + timedelta(days=6)

                # Fetch travel insurance expiring next week
                insurances = ClientTravelInsurance.objects.filter(
                    ref_client__client_status=1,
                    insurance_to_date__gte=monday,
                    insurance_to_date__lte=sunday,
                ).select_related("ref_client")

                if not insurances.exists():
                    logging.warning("No travel insurance expiries found for next week.")
                    return

                report_duration = f"Upcoming Travel Insurance Expiry (From {monday.strftime('%d-%m-%Y')} to {sunday.strftime('%d-%m-%Y')})"

                # Build email content as HTML table
                email_content = f"<h2>MyValueTrip</h2><p>{report_duration}</p>"
                email_content += "<table border='1' cellpadding='5' cellspacing='0'>"
                email_content += "<tr><th>Client Name</th><th>Expiry Date</th></tr>"

                for t in insurances:
                    client = t.ref_client
                    client_name = f"{client.client_salutation or ''} {client.client_first_name or ''} {client.client_middle_name or ''} {client.client_last_name or ''}".strip()
                    expiry_formatted = t.insurance_to_date.strftime("%d-%m-%Y")
                    email_content += f"<tr><td>{client_name}</td><td>{expiry_formatted}</td></tr>"

                email_content += "</table>"

                # Fetch recipients
                recipients = ReportEmail.objects.filter(
                    setup__report_type="insurance_expiry"
                ).values_list("email", flat=True)

                if not recipients:
                    logging.warning("No recipient configured for travel insurance expiry.")
                    return

                # Send email
                email = EmailMessage(
                    subject="Upcoming Travel Insurance Expiry Report",
                    body=email_content,
                    to=list(recipients),
                )
                email.content_subtype = "html"
                email.send()

                logging.info(f"Travel insurance expiry report sent to: {', '.join(recipients)}")
            except Exception as e:
                logging.error(f"Failed to send travel insurance expiry email: {e}")

    cmd = Command()
    cmd.handle()