# Generated by Django 5.2.4 on 2025-09-21 15:07

from django.db import migrations


USER_ADMIN_TASKS = [
    (
        "Review regression: Restore user admin profile sections",
        "/admin/teams/user/",
        (
            "Verify that the Teams user change view once again lists each profile inline "
            "(Odoo, Release Manager, Email Inbox, Email Outbox, Assistant) and that "
            "their user data toggles function as expected."
        ),
    ),
    (
        "Validate screen User admin change view",
        "/admin/teams/user/",
        (
            "Open the Teams user change form and confirm the Release Manager, Email Inbox, "
            "Email Outbox, and Assistant profile panels render with working user datum "
            "controls."
        ),
    ),
]


def _get_manager(model):
    return getattr(model, "all_objects", model._default_manager)


def add_user_admin_tasks(apps, schema_editor):
    Todo = apps.get_model("core", "Todo")
    manager = _get_manager(Todo)

    for request, url, details in USER_ADMIN_TASKS:
        defaults = {
            "url": url,
            "request_details": details,
            "is_seed_data": True,
            "is_deleted": False,
            "is_user_data": False,
            "done_on": None,
            "on_done_condition": "",
        }
        existing = (
            manager.filter(request__iexact=request)
            .order_by("pk")
            .first()
        )
        if existing is None:
            manager.create(request=request, **defaults)
            continue
        updated_fields = []
        for field, value in defaults.items():
            if getattr(existing, field) != value:
                setattr(existing, field, value)
                updated_fields.append(field)
        if updated_fields:
            existing.save(update_fields=updated_fields)


def remove_user_admin_tasks(apps, schema_editor):
    Todo = apps.get_model("core", "Todo")
    manager = _get_manager(Todo)

    qs = manager.filter(request__in=[task[0] for task in USER_ADMIN_TASKS])
    for todo in qs:
        if getattr(todo, "is_seed_data", False):
            todo.is_deleted = True
            todo.save(update_fields=["is_deleted"])
        else:
            todo.delete()


class Migration(migrations.Migration):

    dependencies = [
        ("core", "0041_merge_20250921_0725"),
    ]

    operations = [
        migrations.RunPython(add_user_admin_tasks, remove_user_admin_tasks),
    ]
