from django.core.management.base import BaseCommand
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils import timezone
from datetime import timedelta
from tenants.models import Tenant

class Command(BaseCommand):
    help = 'Send trial expiry notifications to tenants'

    def handle(self, *args, **options):
        now = timezone.now()

        # Notify tenants 3 days before trial expires
        three_days_before = now + timedelta(days=3)
        expiring_soon = Tenant.objects.filter(
            status='trial',
            trial_ends_at__date=three_days_before.date()
        )

        # Notify tenants 1 day before trial expires
        one_day_before = now + timedelta(days=1)
        expiring_tomorrow = Tenant.objects.filter(
            status='trial',
            trial_ends_at__date=one_day_before.date()
        )

        # Send 3-day notifications
        for tenant in expiring_soon:
            self.send_trial_notification(tenant, 3)

        # Send 1-day notifications
        for tenant in expiring_tomorrow:
            self.send_trial_notification(tenant, 1)

        # Update expired trials
        expired_tenants = Tenant.objects.filter(
            status='trial',
            trial_ends_at__lt=now
        )

        for tenant in expired_tenants:
            tenant.status = 'expired'
            tenant.save()
            self.send_trial_expired_notification(tenant)

        self.stdout.write(
            self.style.SUCCESS(f'Processed {expiring_soon.count() + expiring_tomorrow.count()} trial notifications')
        )

    def send_trial_notification(self, tenant, days_remaining):
        subject = f'Your POS App trial expires in {days_remaining} day{"s" if days_remaining > 1 else ""}'

        context = {
            'tenant': tenant,
            'days_remaining': days_remaining,
        }

        html_message = render_to_string('tenants/emails/trial_expiry_warning.html', context)
        plain_message = render_to_string('tenants/emails/trial_expiry_warning.txt', context)

        send_mail(
            subject=subject,
            message=plain_message,
            from_email='pos@optinet.co.ke',
            recipient_list=[tenant.contact_email],
            html_message=html_message,
            fail_silently=False,
        )

    def send_trial_expired_notification(self, tenant):
        subject = 'Your POS App trial has expired - Subscribe to continue'

        context = {'tenant': tenant}

        html_message = render_to_string('tenants/emails/trial_expired.html', context)
        plain_message = render_to_string('tenants/emails/trial_expired.txt', context)

        send_mail(
            subject=subject,
            message=plain_message,
            from_email='pos@optinet.co.ke',
            recipient_list=[tenant.contact_email],
            html_message=html_message,
            fail_silently=False,
        )