# Generated by Codex on 2026-05-23

from django.db import migrations


def backfill_default_project(apps, schema_editor):
    Project = apps.get_model("db", "Project")
    WorkSpace = apps.get_model("db", "WorkSpace")

    for workspace_id in WorkSpace.objects.values_list("id", flat=True).iterator():
        active_projects = Project.objects.filter(
            workspace_id=workspace_id,
            deleted_at__isnull=True,
        )
        if active_projects.filter(is_default=True).exists():
            default_project = active_projects.filter(is_default=True).order_by("created_at", "id").first()
            active_projects.filter(is_default=True).exclude(pk=default_project.pk).update(is_default=False)
            continue

        project = active_projects.order_by("created_at", "id").first()
        if project is not None:
            Project.objects.filter(pk=project.pk).update(is_default=True)


def noop_reverse(apps, schema_editor):
    pass


class Migration(migrations.Migration):
    dependencies = [
        ("db", "0135_project_is_default"),
    ]

    operations = [
        migrations.RunPython(backfill_default_project, noop_reverse),
    ]
