from django.core.management.base import BaseCommand
from django.utils import timezone

from igny8_core.auth.models import Account, Site, Sector
from igny8_core.business.planning.models import Clusters, Keywords, ContentIdeas
from igny8_core.business.content.models import Tasks, Content, Images


class Command(BaseCommand):
    help = "Permanently delete soft-deleted records whose retention window has expired."

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

        models = [
            Account,
            Site,
            Sector,
            Clusters,
            Keywords,
            ContentIdeas,
            Tasks,
            Content,
            Images,
        ]

        for model in models:
            qs = model.all_objects.filter(is_deleted=True, restore_until__lt=now)
            if model is Account:
                qs = qs.exclude(slug='aws-admin')
            count = qs.count()
            if count:
                qs.delete()
                total_deleted += count
                self.stdout.write(self.style.SUCCESS(f"Purged {count} {model.__name__} record(s)."))

        if total_deleted == 0:
            self.stdout.write("No expired soft-deleted records to purge.")
        else:
            self.stdout.write(self.style.SUCCESS(f"Total purged: {total_deleted}"))

