from django.core.management.base import BaseCommand, CommandError
from rest_framework.exceptions import ValidationError
from users.security_models import AccountDeletionRequest
from users.security_deletion import blockers, finalize


class Command(BaseCommand):
    help='Preview or finalize one eligible deletion request; never erase sporting/financial history.'

    def add_arguments(self,parser):
        parser.add_argument('--request-id',required=True)
        parser.add_argument('--apply',action='store_true')

    def handle(self,**options):
        import json
        row=AccountDeletionRequest.objects.select_related('user').filter(pk=options['request_id']).first()
        if row is None:
            raise CommandError('Deletion request not found.')
        if not options['apply']:
            self.stdout.write(json.dumps({'id':str(row.pk),'status':row.status,'eligible_after':row.eligible_after.isoformat(),'blockers':blockers(row.user)}))
            return
        try:
            result=finalize(row.pk)
        except ValidationError as exc:
            raise CommandError(str(exc.detail)) from exc
        self.stdout.write(json.dumps(result))
