import os
import yenv

from django.core.management.base import BaseCommand, CommandError
from django.contrib.auth import get_user_model
from django.core.management import call_command


User = get_user_model()


class Command(BaseCommand):

    help = 'Migrate database and fill with init data.'

    def handle(self, *args, **options):
        if yenv.type != 'development':
            raise CommandError('Use this command only locally')

        call_command('migrate')

        User.objects.get_or_create(
            username=os.environ['STAFF_USERNAME'],
            defaults={
                'is_staff': True,
                'is_superuser': True,
            },
        )
        for f in sorted(os.listdir('data')):
            call_command('loaddata', os.path.join('data', f))
