import json

from django.core.management.base import BaseCommand

from topdownrbac.services.perm_consistency_check_service import UserPermissionConsistencyService


class Command(BaseCommand):
    help = ("""Check consistency off UserPermission table to avoid ghost or missing permissions.
            Depending on the size of your application, this can be a heavy task and it is recommended
            to run it on schedule or asynchronously. Use the update flag to apply changes necessary
            to have a consistent permission table.""")

    def add_arguments(self, parser):
        parser.add_argument("--update", "-u", action="store_true")

    def handle(self, *args, **options):
        service = UserPermissionConsistencyService(options["update"])
        summary = service.run()
        if summary["total_operations"]==0:
            self.stdout.write(self.style.SUCCESS("UserPermission table is consistent with the role bindings."))
        else:
            self.stdout.write(self.style.WARNING("""UserPermission table is inconsistent with the role bindings.
            Here is the detailed report: \n""" + json.dumps(summary)))
