"""Management command to create a platform admin user."""
from django.core.management.base import BaseCommand
from rest_framework.authtoken.models import Token

from smoothschedule.identity.users.models import User


class Command(BaseCommand):
    """Create a platform admin user for testing."""

    help = "Create a platform admin user with authentication token"

    def handle(self, *args, **options):
        """Create or update the admin user."""
        # Create or get a superuser with platform admin role
        user, created = User.objects.get_or_create(
            username="admin",
            defaults={
                "email": "admin@smoothschedule.com",
                "is_staff": True,
                "is_superuser": True,
                "role": User.Role.SUPERUSER,
            },
        )

        if created:
            user.set_password("admin123")
            user.save()
            self.stdout.write(
                self.style.SUCCESS(f"Created new superuser: {user.username}")
            )
        else:
            user.role = User.Role.SUPERUSER
            user.is_staff = True
            user.is_superuser = True
            user.set_password("admin123")
            user.save()
            self.stdout.write(
                self.style.SUCCESS(f"Updated existing user: {user.username}")
            )

        # Create or get auth token
        token, _ = Token.objects.get_or_create(user=user)
        self.stdout.write(f"\nAuth token: {token.key}")
        self.stdout.write(f"User role: {user.role}")
        self.stdout.write("\nYou can now use this token to test the API:")
        self.stdout.write(
            f'curl -H "Authorization: Token {token.key}" http://lvh.me:8000/api/platform/businesses/'
        )
