from django.core.management.base import BaseCommand
from houseteli_administrator.h_admin.models import ServiceType, Identity, Frontend
from django.conf import settings

class Command(BaseCommand):
    help = 'Create default ServiceType, Identity, and Frontend instances'

    def handle(self, *args, **kwargs):
        # Create the default 'auth' ServiceType if it doesn't exist
        service_type, created = ServiceType.objects.get_or_create(
            name='auth',
            defaults={'description': 'Authentication Service'}
        )
        
        if created:
            self.stdout.write(self.style.SUCCESS("Created default 'auth' ServiceType"))
        else:
            self.stdout.write(self.style.SUCCESS("'auth' ServiceType already exists"))
        
        # Create the default Frontend instance if it doesn't exist
        if not Frontend.objects.exists():
            frontend = Frontend.objects.create(
                flow_title='Default Flow Title',
                flow_description='Default description for the flow.',
                switch_description='Default switch description.',
                sign_in_description='Default sign-in description.',
                register_description='Default register description.',
                forgot_description='Default forgot description.',
                reset_description='Default reset description.',
                authenticated_route='/dashboard/'
                account_type='Defaut Account Type'
            )
            self.stdout.write(self.style.SUCCESS(f"Created Frontend: {frontend.flow_title}"))
        else:
            self.stdout.write(self.style.SUCCESS("Frontend instance already exists"))

        # Check if the Identity instance exists, if not, create it
        if not Identity.objects.exists():
            identity_name = getattr(settings, 'SERVICE_NAME', 'anon')
            identity_description = f"{identity_name} Service"  # Custom description logic

            identity = Identity.objects.create(
                name=identity_name,
                description=identity_description,
                enable_admin=True,
                service_type=service_type,
                frontend=frontend  # Link the frontend to the identity
            )

            self.stdout.write(self.style.SUCCESS(f"Created Identity: {identity.name}"))
        else:
            self.stdout.write(self.style.SUCCESS("Identity instance already exists"))
