# Generated by Django 5.2.8 on 2025-11-11 02:39

from django.db import migrations, models
import django.utils.timezone


def ensure_todo_created_on(apps, schema_editor):
    """Add the ``created_on`` column when missing and backfill timestamps."""

    Todo = apps.get_model("core", "Todo")
    table = Todo._meta.db_table
    connection = schema_editor.connection

    with connection.cursor() as cursor:
        existing_columns = {
            column.name
            for column in connection.introspection.get_table_description(cursor, table)
        }

    if "created_on" in existing_columns:
        return

    field = models.DateTimeField(auto_now_add=True, null=True)
    field.set_attributes_from_name("created_on")
    schema_editor.add_field(Todo, field)

    timestamp = django.utils.timezone.now()
    with connection.cursor() as cursor:
        cursor.execute(
            f"UPDATE {schema_editor.quote_name(table)} "
            f"SET {schema_editor.quote_name('created_on')} = ? "
            f"WHERE {schema_editor.quote_name('created_on')} IS NULL",
            [timestamp],
        )


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0094_remove_evmodel_brand_remove_electricvehicle_brand_and_more"),
    ]

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