"""
Management command to reset the database and create an admin user.

Security Note: This command uses a mix of raw SQL (for PostgreSQL-specific operations
like dropping all tables) and Django ORM (for creating users). The raw SQL operations
use quote_ident() for table/sequence names which is safe from SQL injection.

WARNING: This command is destructive and should only be used in development.
"""

from django.core.management.base import BaseCommand
from django.db import connection


class Command(BaseCommand):
    help = "Reset database and create admin user"

    def handle(self, *args, **options):
        self.stdout.write("Resetting database...")

        # Drop all tables using PostgreSQL-specific operations
        # Security: Using quote_ident() to safely quote table/sequence names
        with connection.cursor() as cursor:
            cursor.execute(
                """
                DO $$ DECLARE
                    r RECORD;
                BEGIN
                    FOR r IN (
                        SELECT tablename FROM pg_tables
                        WHERE schemaname = current_schema()
                    ) LOOP
                        EXECUTE 'DROP TABLE IF EXISTS ' ||
                                quote_ident(r.tablename) || ' CASCADE';
                    END LOOP;
                END $$;
            """
            )

            # Reset sequences
            cursor.execute(
                """
                DO $$ DECLARE
                    r RECORD;
                BEGIN
                    FOR r IN (
                        SELECT sequencename FROM pg_sequences
                        WHERE schemaname = current_schema()
                    ) LOOP
                        EXECUTE 'ALTER SEQUENCE ' ||
                                quote_ident(r.sequencename) || ' RESTART WITH 1';
                    END LOOP;
                END $$;
            """
            )

        self.stdout.write("All tables dropped and sequences reset.")

        # Run migrations
        from django.core.management import call_command

        call_command("migrate")

        self.stdout.write("Migrations applied.")

        # Create superuser using Django ORM (safer than raw SQL)
        try:
            from apps.accounts.models import User, UserProfile

            # Security: Using Django ORM instead of raw SQL for user creation
            user = User.objects.create_superuser(
                username="admin",
                email="admin@thrillwiki.com",
                password="admin",
                role="SUPERUSER",
            )

            # Create profile using ORM
            UserProfile.objects.create(
                user=user,
                display_name="Admin",
                pronouns="they/them",
                bio="ThrillWiki Administrator",
            )

            self.stdout.write("Superuser created.")
        except Exception as e:
            self.stdout.write(self.style.ERROR(f"Error creating superuser: {str(e)}"))
            raise

        self.stdout.write(self.style.SUCCESS("Database reset complete."))
