# Generated by Django 5.0.4 on 2024-08-03 16:35

from django.db import migrations, connection
from django.db import connections as djcs
from explorer import app_settings


def populate_new_foreign_key(apps, _):
    from explorer.app_settings import EXPLORER_DEFAULT_CONNECTION
    DatabaseConnection = apps.get_model('explorer', 'DatabaseConnection')

    # Create new connection for each based on EXPLORER_CONNECTIONS
    connections = [c for c in djcs if c in app_settings.EXPLORER_CONNECTIONS.values()]
    for c in connections:
        if not DatabaseConnection.objects.filter(alias=c).exists():
            is_default = c == EXPLORER_DEFAULT_CONNECTION
            obj = DatabaseConnection(
                alias=c,
                name=c,
                engine="django_connection",
                default=is_default
            )
            obj.save()
            print(f"created Connection ID {obj.id} for {obj.alias}")

    has_default = DatabaseConnection.objects.filter(default=True).exists()
    if not has_default:
        dbc = DatabaseConnection.objects.all().first()
        if dbc:
            dbc.default = True
            dbc.save()

    # These are written as raw SQL rather than queryset updates because e.g. Query.connection is no longer
    # referencable as it was removed from the codebase.
    with connection.cursor() as cursor:
        for c in DatabaseConnection.objects.all():
            # Update Query table
            cursor.execute("""
                UPDATE explorer_query
                SET database_connection_id = %s
                WHERE connection = %s
            """, [c.id, c.alias])

            # Update QueryLog table
            cursor.execute("""
                UPDATE explorer_querylog
                SET database_connection_id = %s
                WHERE connection = %s
            """, [c.id, c.alias])

        if EXPLORER_DEFAULT_CONNECTION:
            default_conn = DatabaseConnection.objects.filter(alias=EXPLORER_DEFAULT_CONNECTION).first()
            if default_conn:
                cursor.execute("""
                    UPDATE explorer_query
                    SET database_connection_id = %s
                    WHERE connection = ''
                """, [default_conn.id])

                cursor.execute("""
                    UPDATE explorer_querylog
                    SET database_connection_id = %s
                    WHERE connection = ''
                """, [default_conn.id])


class Migration(migrations.Migration):

    dependencies = [
        ('explorer', '0023_query_database_connection_and_more'),
    ]

    operations = [
        migrations.RunPython(populate_new_foreign_key),
    ]
