# Generated by Django 5.1.10 on 2025-08-17 08:16

import django.contrib.auth.models
import django.contrib.auth.validators
import django.utils.timezone
from django.db import migrations, models



def rename_auth_user_tables(apps, schema_editor):
    db_vendor = schema_editor.connection.vendor

    tables = schema_editor.connection.introspection.table_names()

    if "auth_user" not in tables and "access_centurionuser" in tables:
        return

    # As this model was changed after app released, the migration is conditionally run.
    migrations.CreateModel(
        name="CenturionUser",
        fields=[
            (
                "id",
                models.BigAutoField(
                    auto_created=True,
                    primary_key=True,
                    serialize=False,
                    verbose_name="ID",
                ),
            ),
            ("password", models.CharField(max_length=128, verbose_name="password")),
            (
                "last_login",
                models.DateTimeField(
                    blank=True, null=True, verbose_name="last login"
                ),
            ),
            (
                "is_superuser",
                models.BooleanField(
                    default=False,
                    help_text="Designates that this user has all permissions without explicitly assigning them.",
                    verbose_name="superuser status",
                ),
            ),
            (
                "username",
                models.CharField(
                    error_messages={
                        "unique": "A user with that username already exists."
                    },
                    help_text="Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.",
                    max_length=150,
                    unique=True,
                    validators=[
                        django.contrib.auth.validators.UnicodeUsernameValidator()
                    ],
                    verbose_name="username",
                ),
            ),
            (
                "first_name",
                models.CharField(
                    blank=True, max_length=150, verbose_name="first name"
                ),
            ),
            (
                "last_name",
                models.CharField(
                    blank=True, max_length=150, verbose_name="last name"
                ),
            ),
            (
                "email",
                models.EmailField(
                    blank=True, max_length=254, verbose_name="email address"
                ),
            ),
            (
                "is_staff",
                models.BooleanField(
                    default=False,
                    help_text="Designates whether the user can log into this admin site.",
                    verbose_name="staff status",
                ),
            ),
            (
                "is_active",
                models.BooleanField(
                    default=True,
                    help_text="Designates whether this user should be treated as active. Unselect this instead of deleting accounts.",
                    verbose_name="active",
                ),
            ),
            (
                "date_joined",
                models.DateTimeField(
                    default=django.utils.timezone.now, verbose_name="date joined"
                ),
            ),
            (
                "groups",
                models.ManyToManyField(
                    blank=True,
                    help_text="The groups this user belongs to. A user will get all permissions granted to each of their groups.",
                    related_name="user_set",
                    related_query_name="user",
                    to="auth.group",
                    verbose_name="groups",
                ),
            ),
            (
                "user_permissions",
                models.ManyToManyField(
                    blank=True,
                    help_text="Specific permissions for this user.",
                    related_name="user_set",
                    related_query_name="user",
                    to="auth.permission",
                    verbose_name="user permissions",
                ),
            ),
        ],
        options={
            "verbose_name": "Centurion User",
            "verbose_name_plural": "Centurion Users",
            "swappable": "AUTH_USER_MODEL",
        },
        managers=[
            ("objects", django.contrib.auth.models.UserManager()),
        ],
    )

    if db_vendor == "sqlite":
        with schema_editor.connection.cursor() as cursor:
            cursor.execute("PRAGMA foreign_keys=off;")

            # --- Main user table ---
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='auth_user';")
            if cursor.fetchone():
                cursor.execute("ALTER TABLE auth_user RENAME TO access_centurionuser;")

            # --- Groups M2M ---
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='auth_user_groups';")
            if cursor.fetchone():
                # rename old table
                cursor.execute("ALTER TABLE auth_user_groups RENAME TO auth_user_groups_old;")
                # create new one with correct schema
                cursor.execute("""
                    CREATE TABLE access_centurionuser_groups (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        centurionuser_id INTEGER NOT NULL REFERENCES access_centurionuser(id) DEFERRABLE INITIALLY DEFERRED,
                        group_id INTEGER NOT NULL REFERENCES auth_group(id) DEFERRABLE INITIALLY DEFERRED
                    );
                """)
                # copy data
                cursor.execute("""
                    INSERT INTO access_centurionuser_groups (id, centurionuser_id, group_id)
                    SELECT id, user_id, group_id FROM auth_user_groups_old;
                """)
                cursor.execute("DROP TABLE auth_user_groups_old;")

            # --- Permissions M2M ---
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table' AND name='auth_user_user_permissions';")
            if cursor.fetchone():
                cursor.execute("ALTER TABLE auth_user_user_permissions RENAME TO auth_user_user_permissions_old;")
                cursor.execute("""
                    CREATE TABLE access_centurionuser_user_permissions (
                        id INTEGER PRIMARY KEY AUTOINCREMENT,
                        centurionuser_id INTEGER NOT NULL REFERENCES access_centurionuser(id) DEFERRABLE INITIALLY DEFERRED,
                        permission_id INTEGER NOT NULL REFERENCES auth_permission(id) DEFERRABLE INITIALLY DEFERRED
                    );
                """)
                cursor.execute("""
                    INSERT INTO access_centurionuser_user_permissions (id, centurionuser_id, permission_id)
                    SELECT id, user_id, permission_id FROM auth_user_user_permissions_old;
                """)
                cursor.execute("DROP TABLE auth_user_user_permissions_old;")


            # Rename M2M Fields
            cursor.execute(
                "ALTER TABLE core_ticket_assigned_users RENAME COLUMN user_id TO centurionuser_id;"
            )
            cursor.execute(
                "ALTER TABLE core_ticket_subscribed_users RENAME COLUMN user_id TO centurionuser_id;"
            )
            cursor.execute(
                "ALTER TABLE project_management_project_team_members RENAME COLUMN user_id TO centurionuser_id;"
            )


            cursor.execute("PRAGMA foreign_keys=on;")

    elif db_vendor == "postgresql":
        with schema_editor.connection.cursor() as cursor:
            cursor.execute("ALTER TABLE IF EXISTS auth_user RENAME TO access_centurionuser;")
            cursor.execute("ALTER TABLE IF EXISTS auth_user_groups RENAME TO access_centurionuser_groups;")
            cursor.execute("ALTER TABLE IF EXISTS access_centurionuser_groups RENAME COLUMN user_id TO centurionuser_id;")
            cursor.execute("ALTER TABLE IF EXISTS auth_user_user_permissions RENAME TO access_centurionuser_user_permissions;")
            cursor.execute("ALTER TABLE IF EXISTS access_centurionuser_user_permissions RENAME COLUMN user_id TO centurionuser_id;")

            # Rename M2M Fields
            cursor.execute(
                "ALTER TABLE core_ticket_assigned_users RENAME COLUMN user_id TO centurionuser_id;"
            )
            cursor.execute(
                "ALTER TABLE core_ticket_subscribed_users RENAME COLUMN user_id TO centurionuser_id;"
            )
            cursor.execute(
                "ALTER TABLE project_management_project_team_members RENAME COLUMN user_id TO centurionuser_id;"
            )

    elif db_vendor == "mysql":
        with schema_editor.connection.cursor() as cursor:
            cursor.execute("RENAME TABLE auth_user TO access_centurionuser;")
            cursor.execute("RENAME TABLE auth_user_groups TO access_centurionuser_groups;")
            cursor.execute("RENAME TABLE auth_user_user_permissions TO access_centurionuser_user_permissions;")

            try:
                cursor.execute("ALTER TABLE access_centurionuser_groups RENAME COLUMN user_id TO centurionuser_id;")
            except Exception:
                cursor.execute("ALTER TABLE access_centurionuser_groups CHANGE user_id centurionuser_id bigint NOT NULL;")

            try:
                cursor.execute("ALTER TABLE access_centurionuser_user_permissions RENAME COLUMN user_id TO centurionuser_id;")
            except Exception:
                cursor.execute("ALTER TABLE access_centurionuser_user_permissions CHANGE user_id centurionuser_id bigint NOT NULL;")

            # Rename M2M Fields
            cursor.execute(
                "ALTER TABLE core_ticket_assigned_users RENAME COLUMN user_id TO centurionuser_id;"
            )
            cursor.execute(
                "ALTER TABLE core_ticket_subscribed_users RENAME COLUMN user_id TO centurionuser_id;"
            )
            cursor.execute(
                "ALTER TABLE project_management_project_team_members RENAME COLUMN user_id TO centurionuser_id;"
            )

    else:
        raise RuntimeError(f"Unsupported DB vendor: {db_vendor}")



class Migration(migrations.Migration):

    dependencies = [
        ("access", "0011_remove_entitynotes_model_and_more"),
        ("auth", "0011_update_proxy_permissions"),
    ]

    operations = [
        migrations.RunPython(rename_auth_user_tables, migrations.RunPython.noop),
    ]
