from django.db import migrations


def reset_sequence(apps, schema_editor):
    from django.db import connection

    with connection.cursor() as cursor:
        vendor = connection.vendor
        if vendor == "postgresql":
            cursor.execute(
                "SELECT setval('scrobbles_ebirdcsvimport_id_seq', "
                "COALESCE((SELECT MAX(id) + 1 FROM scrobbles_ebirdcsvimport), 1), "
                "false)"
            )
        elif vendor == "sqlite":
            cursor.execute(
                "UPDATE sqlite_sequence SET seq = ("
                "SELECT COALESCE(MAX(id), 0) FROM scrobbles_ebirdcsvimport"
                ") WHERE name = 'scrobbles_ebirdcsvimport'"
            )


class Migration(migrations.Migration):
    dependencies = [
        ("scrobbles", "0083_migrate_birding_data"),
    ]

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