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

from admissions.models import Application


class Command(BaseCommand):
    help = 'Delete applications stuck in awaiting_payment for more than 24 hours.'

    def add_arguments(self, parser):
        parser.add_argument(
            '--hours', type=int, default=24,
            help='Delete applications older than this many hours (default: 24).',
        )
        parser.add_argument(
            '--dry-run', action='store_true',
            help='Show what would be deleted without actually deleting.',
        )

    def handle(self, *args, **options):
        hours = options['hours']
        dry_run = options['dry_run']
        cutoff = timezone.now() - timedelta(hours=hours)

        qs = Application.objects.filter(
            status=Application.AWAITING_PAYMENT,
            submitted_at__lt=cutoff,
        )

        count = qs.count()
        if count == 0:
            self.stdout.write('No stale unpaid applications found.')
            return

        if dry_run:
            self.stdout.write(f'[DRY RUN] Would delete {count} application(s):')
            for app in qs:
                self.stdout.write(f'  - {app.reference_number} | {app.full_name} | submitted {app.submitted_at}')
        else:
            qs.delete()
            self.stdout.write(
                self.style.SUCCESS(f'Deleted {count} unpaid application(s) older than {hours} hours.')
            )
