from django.contrib.auth.models import Group, Permission, User
from django.core.management.base import BaseCommand


class Command(BaseCommand):
    help = "Creates test users for e2e testing"

    def handle(self, *args, **kwargs):
        # Create regular test user
        if not User.objects.filter(username="testuser").exists():
            user = User.objects.create(
                username="testuser",
                email="testuser@example.com",
            )
            user.set_password("testpass123")
            user.save()
            self.stdout.write(self.style.SUCCESS(f"Created test user: {user.get_username()}"))
        else:
            self.stdout.write(self.style.WARNING("Test user already exists"))

        if not User.objects.filter(username="moderator").exists():
            moderator = User.objects.create(
                username="moderator",
                email="moderator@example.com",
            )
            moderator.set_password("modpass123")
            moderator.save()

            # Create moderator group if it doesn't exist
            moderator_group, created = Group.objects.get_or_create(name="Moderators")

            # Add relevant permissions
            permissions = Permission.objects.filter(
                codename__in=[
                    "change_review",
                    "delete_review",
                    "change_park",
                    "change_ride",
                    "moderate_photos",
                    "moderate_comments",
                ]
            )
            moderator_group.permissions.add(*permissions)

            # Add user to moderator group
            moderator.groups.add(moderator_group)

            self.stdout.write(self.style.SUCCESS(f"Created moderator user: {moderator.get_username()}"))
        else:
            self.stdout.write(self.style.WARNING("Moderator user already exists"))

        self.stdout.write(self.style.SUCCESS("Test users setup complete"))
