"""
ADDITIVE: expire companies whose subscription / trial has ended.

  python manage.py enforce_subscription_expiry --dry-run
  python manage.py enforce_subscription_expiry --grace-days 3

Policy: a company is expired when the relevant end date is more than
--grace-days in the past. ACTIVE companies use subscription_end_date,
TRIAL companies use trial_end_date. Expired companies get
company_status=EXPIRED and status=False (company login is then refused).
Schedule daily with cron.
"""
from datetime import timedelta

from django.core.management.base import BaseCommand
from django.utils import timezone

from Company.models import company_details
from SuperAdmin.models import SuperAdminAuditLog


class Command(BaseCommand):
    help = "Expire companies whose subscription or trial ended (policy: grace days)."

    def add_arguments(self, parser):
        parser.add_argument("--grace-days", type=int, default=0)
        parser.add_argument("--dry-run", action="store_true")

    def handle(self, *args, **opts):
        cutoff = timezone.localdate() - timedelta(days=max(opts["grace_days"], 0))
        targets = list(
            company_details.objects.filter(
                company_status="ACTIVE", subscription_end_date__lt=cutoff
            )
        ) + list(
            company_details.objects.filter(
                company_status="TRIAL", trial_end_date__lt=cutoff
            )
        )
        for c in targets:
            self.stdout.write(f"{'[dry-run] ' if opts['dry_run'] else ''}expire {c.company_id} {c.Registered_Company_Name}")
            if opts["dry_run"]:
                continue
            c.company_status = "EXPIRED"
            c.status = False
            c.save(update_fields=["company_status", "status"])
            SuperAdminAuditLog.objects.create(
                company=c, action="OTHER",
                description="Auto-expired by enforce_subscription_expiry",
                created_by="system",
            )
        self.stdout.write(self.style.SUCCESS(f"{len(targets)} compan(ies) processed."))

 
