from django.core.management.base import BaseCommand
from django.db import connections
from django.db.models import Q, F, Value
from django.db.models.functions import ConcatPair
from establishment.management.commands.add_position import namedtuplefetchall
from account.models import User


class Command(BaseCommand):
    help = 'Add account from old db to new db'

    def account_sql(self):
        with connections['legacy'].cursor() as cursor:
            cursor.execute('''
                            select a.email, a.id as account_id, a.encrypted_password, 
                            case when a.confirmed_at is not null then true else false end as confirmed_at,
                            case when a.confirmed_at is null then true else false end as unconfirmed_email,                            
                            nickname  
                            from accounts as a 
                            where a.email is not null and a.nickname!='admin'                                                               
            ''')
            return namedtuplefetchall(cursor)

    def handle(self,  *args, **kwargs):
        objects = []
        for a in self.account_sql():
            users = User.objects.filter(Q(email=a.email) | Q(old_id=a.account_id))
            if not users.exists():
                objects.append(User(email=a.email,
                                    unconfirmed_email=a.unconfirmed_email,
                                    email_confirmed=a.confirmed_at,
                                    old_id=a.account_id,
                                    password=a.encrypted_password,
                                    username=a.nickname
                                    ))

        User.objects.bulk_create(objects)
        user = User.objects.filter(old_id__isnull=False)
        user.update(password=ConcatPair(Value('bcrypt$'), F('password')))
        self.stdout.write(self.style.WARNING(f'Created accounts objects.'))
