"""Management command to create test users for each role."""
from django.core.management.base import BaseCommand
from rest_framework.authtoken.models import Token

from smoothschedule.identity.core.models import Tenant
from smoothschedule.identity.users.models import User


class Command(BaseCommand):
    """Create test users for each role type."""

    help = "Create test users for development and testing"

    def handle(self, *args, **options):
        """Create test users for each role."""

        # Get or create a demo tenant
        demo_tenant, _ = Tenant.objects.get_or_create(
            schema_name='demo',
            defaults={'name': 'Demo Company'}
        )

        test_users = [
            # Platform users (no tenant) - username is set to email
            {
                'username': 'superuser@platform.com',
                'email': 'superuser@platform.com',
                'password': 'test123',
                'role': User.Role.SUPERUSER,
                'first_name': 'Super',
                'last_name': 'User',
                'tenant': None,
            },
            {
                'username': 'manager@platform.com',
                'email': 'manager@platform.com',
                'password': 'test123',
                'role': User.Role.PLATFORM_MANAGER,
                'first_name': 'Platform',
                'last_name': 'Manager',
                'tenant': None,
            },
            {
                'username': 'sales@platform.com',
                'email': 'sales@platform.com',
                'password': 'test123',
                'role': User.Role.PLATFORM_SALES,
                'first_name': 'Sales',
                'last_name': 'Rep',
                'tenant': None,
            },
            {
                'username': 'support@platform.com',
                'email': 'support@platform.com',
                'password': 'test123',
                'role': User.Role.PLATFORM_SUPPORT,
                'first_name': 'Support',
                'last_name': 'Agent',
                'tenant': None,
            },
            # Tenant users (with tenant) - username is set to email
            {
                'username': 'owner@demo.com',
                'email': 'owner@demo.com',
                'password': 'test123',
                'role': User.Role.TENANT_OWNER,
                'first_name': 'Business',
                'last_name': 'Owner',
                'tenant': demo_tenant,
            },
            {
                'username': 'manager@demo.com',
                'email': 'manager@demo.com',
                'password': 'test123',
                'role': User.Role.TENANT_MANAGER,
                'first_name': 'Business',
                'last_name': 'Manager',
                'tenant': demo_tenant,
            },
            {
                'username': 'staff@demo.com',
                'email': 'staff@demo.com',
                'password': 'test123',
                'role': User.Role.TENANT_STAFF,
                'first_name': 'Staff',
                'last_name': 'Member',
                'tenant': demo_tenant,
            },
            {
                'username': 'customer@demo.com',
                'email': 'customer@demo.com',
                'password': 'test123',
                'role': User.Role.CUSTOMER,
                'first_name': 'Customer',
                'last_name': 'User',
                'tenant': demo_tenant,
            },
        ]

        self.stdout.write("\n" + "="*60)
        self.stdout.write("Creating Test Users")
        self.stdout.write("="*60 + "\n")

        for user_data in test_users:
            username = user_data['username']
            user, created = User.objects.get_or_create(
                username=username,
                defaults=user_data
            )

            if created:
                user.set_password(user_data['password'])
                user.save()
                status = self.style.SUCCESS("CREATED")
            else:
                # Update existing user
                for key, value in user_data.items():
                    if key != 'password':
                        setattr(user, key, value)
                user.set_password(user_data['password'])
                user.save()
                status = self.style.WARNING("UPDATED")

            # Create auth token
            token, _ = Token.objects.get_or_create(user=user)

            tenant_info = f"tenant={user.tenant.name}" if user.tenant else "platform user"
            self.stdout.write(
                f"{status} {username:20} | {user.role:20} | {tenant_info:20} | token={token.key}"
            )

        self.stdout.write("\n" + "="*60)
        self.stdout.write(self.style.SUCCESS("All test users created successfully!"))
        self.stdout.write("="*60 + "\n")
        self.stdout.write("\nAll passwords: test123\n")
