from django.db import migrations


def forward_fix_admin_log_fk(apps, schema_editor):
    if schema_editor.connection.vendor != "postgresql":
        return
    schema_editor.execute(
        """
        ALTER TABLE django_admin_log
        DROP CONSTRAINT IF EXISTS django_admin_log_user_id_c564eba6_fk_auth_user_id;
        """
    )
    schema_editor.execute(
        """
        UPDATE django_admin_log
        SET user_id = sub.new_user_id
        FROM (
            SELECT id AS new_user_id
            FROM igny8_users
            ORDER BY id
            LIMIT 1
        ) AS sub
        WHERE django_admin_log.user_id NOT IN (
            SELECT id FROM igny8_users
        );
        """
    )
    schema_editor.execute(
        """
        ALTER TABLE django_admin_log
        ADD CONSTRAINT django_admin_log_user_id_c564eba6_fk_igny8_users_id
        FOREIGN KEY (user_id) REFERENCES igny8_users(id) DEFERRABLE INITIALLY DEFERRED;
        """
    )


def reverse_fix_admin_log_fk(apps, schema_editor):
    if schema_editor.connection.vendor != "postgresql":
        return
    schema_editor.execute(
        """
        ALTER TABLE django_admin_log
        DROP CONSTRAINT IF EXISTS django_admin_log_user_id_c564eba6_fk_igny8_users_id;
        """
    )
    schema_editor.execute(
        """
        UPDATE django_admin_log
        SET user_id = sub.old_user_id
        FROM (
            SELECT id AS old_user_id
            FROM auth_user
            ORDER BY id
            LIMIT 1
        ) AS sub
        WHERE django_admin_log.user_id NOT IN (
            SELECT id FROM auth_user
        );
        """
    )
    schema_editor.execute(
        """
        ALTER TABLE django_admin_log
        ADD CONSTRAINT django_admin_log_user_id_c564eba6_fk_auth_user_id
        FOREIGN KEY (user_id) REFERENCES auth_user(id) DEFERRABLE INITIALLY DEFERRED;
        """
    )


class Migration(migrations.Migration):

    dependencies = [
        ("igny8_core_auth", "0008_passwordresettoken_alter_industry_options_and_more"),
    ]

    operations = [
        migrations.RunPython(forward_fix_admin_log_fk, reverse_fix_admin_log_fk),
    ]


