from django.core.management.base import BaseCommand
from tqdm import tqdm

from account.models import User, UserRole, Role
from transfer.models import OwnershipAffs
from establishment.models import Establishment


class Command(BaseCommand):
    help = """Add ownership to UserRoles."""

    def handle(self, *args, **kwarg):
        create_user_roles = []
        # filter owner records with state not null only
        owners = OwnershipAffs.objects.filter(state__isnull=False)

        # Get role, may be more then 1
        role = Role.objects.filter(role=Role.ESTABLISHMENT_MANAGER).first()
        if not role:
            role = Role.objects.create(
                role=Role.ESTABLISHMENT_MANAGER
            )

        for owner in tqdm(owners):
            user = User.objects.filter(
                old_id=owner.account_id).first()
            requester = User.objects.filter(
                old_id=owner.requester_id).first()
            establishment = Establishment.objects.filter(
                old_id=owner.establishment_id).first()

            if user and establishment:
                user_role = UserRole.objects.filter(
                    user=user, role=role, establishment=establishment, state=owner.state).first()
                if not user_role:
                    # add to bulk_create
                    create_user_roles.append(UserRole(
                        user=user,
                        role=role,
                        establishment=establishment,
                        state=owner.state,
                        requester=requester
                    ))

        UserRole.objects.bulk_create(create_user_roles)
        self.stdout.write(
            self.style.WARNING(
                f'Created roles: {len(create_user_roles)}')
        )
