# Generated by Django 5.2.11 on 2026-02-20 22:05

from collections import defaultdict

from django.db import migrations
from django.db import models

# from src-ui/src/app/data/ui-settings.ts
SAVED_VIEWS_KEY = "saved_views"
DASHBOARD_VIEWS_VISIBLE_IDS_KEY = "dashboard_views_visible_ids"
SIDEBAR_VIEWS_VISIBLE_IDS_KEY = "sidebar_views_visible_ids"


def _parse_visible_ids(raw_value) -> set[int]:
    """Return integer SavedView IDs parsed from a JSON list value."""
    if not isinstance(raw_value, list):
        return set()

    parsed_ids = set()
    for raw_id in raw_value:
        raw_id_string = str(raw_id)
        if raw_id_string.isdigit():
            parsed_ids.add(int(raw_id_string))
    return parsed_ids


def _set_default_visibility_ids(apps, schema_editor):
    """
    Move SavedView visibility from boolean model props into JSON UiSettings.settings.saved_views, specifically:
      settings.saved_views.dashboard_views_visible_ids
      settings.saved_views.sidebar_views_visible_ids
    """
    SavedView = apps.get_model("documents", "SavedView")
    UiSettings = apps.get_model("documents", "UiSettings")
    User = apps.get_model("auth", "User")

    dashboard_visible_ids_by_owner: defaultdict[int, list[int]] = defaultdict(list)
    for owner_id, view_id in SavedView.objects.filter(
        owner__isnull=False,
        show_on_dashboard=True,
    ).values_list("owner_id", "id"):
        dashboard_visible_ids_by_owner[owner_id].append(view_id)

    sidebar_visible_ids_by_owner: defaultdict[int, list[int]] = defaultdict(list)
    for owner_id, view_id in SavedView.objects.filter(
        owner__isnull=False,
        show_in_sidebar=True,
    ).values_list("owner_id", "id"):
        sidebar_visible_ids_by_owner[owner_id].append(view_id)

    for user in User.objects.all():
        ui_settings, _ = UiSettings.objects.get_or_create(
            user=user,
            defaults={"settings": {}},
        )
        current_settings = ui_settings.settings
        if not isinstance(current_settings, dict):
            current_settings = {}

        changed = False
        saved_views_settings = current_settings.get(SAVED_VIEWS_KEY)
        if not isinstance(saved_views_settings, dict):
            saved_views_settings = {}
            changed = True

        if saved_views_settings.get(DASHBOARD_VIEWS_VISIBLE_IDS_KEY) is None:
            saved_views_settings[DASHBOARD_VIEWS_VISIBLE_IDS_KEY] = (
                dashboard_visible_ids_by_owner.get(user.id, [])
            )
            changed = True

        if saved_views_settings.get(SIDEBAR_VIEWS_VISIBLE_IDS_KEY) is None:
            saved_views_settings[SIDEBAR_VIEWS_VISIBLE_IDS_KEY] = (
                sidebar_visible_ids_by_owner.get(user.id, [])
            )
            changed = True

        current_settings[SAVED_VIEWS_KEY] = saved_views_settings

        if changed:
            ui_settings.settings = current_settings
            ui_settings.save(update_fields=["settings"])


def _restore_visibility_fields(apps, schema_editor):
    SavedView = apps.get_model("documents", "SavedView")
    UiSettings = apps.get_model("documents", "UiSettings")

    dashboard_visible_ids_by_owner: dict[int, set[int]] = {}
    sidebar_visible_ids_by_owner: dict[int, set[int]] = {}
    for ui_settings in UiSettings.objects.all():
        current_settings = ui_settings.settings
        if not isinstance(current_settings, dict):
            continue
        saved_views_settings = current_settings.get(SAVED_VIEWS_KEY)
        if not isinstance(saved_views_settings, dict):
            saved_views_settings = {}

        dashboard_visible_ids_by_owner[ui_settings.user_id] = _parse_visible_ids(
            saved_views_settings.get(DASHBOARD_VIEWS_VISIBLE_IDS_KEY),
        )

        sidebar_visible_ids_by_owner[ui_settings.user_id] = _parse_visible_ids(
            saved_views_settings.get(SIDEBAR_VIEWS_VISIBLE_IDS_KEY),
        )

    SavedView.objects.update(show_on_dashboard=False, show_in_sidebar=False)
    for owner_id, dashboard_visible_ids in dashboard_visible_ids_by_owner.items():
        if not dashboard_visible_ids:
            continue
        SavedView.objects.filter(
            owner_id=owner_id,
            id__in=dashboard_visible_ids,
        ).update(
            show_on_dashboard=True,
        )
    for owner_id, sidebar_visible_ids in sidebar_visible_ids_by_owner.items():
        if not sidebar_visible_ids:
            continue
        SavedView.objects.filter(owner_id=owner_id, id__in=sidebar_visible_ids).update(
            show_in_sidebar=True,
        )


class Migration(migrations.Migration):
    dependencies = [
        ("documents", "0013_alter_paperlesstask_task_name"),
    ]

    operations = [
        migrations.AlterField(
            model_name="savedview",
            name="show_on_dashboard",
            field=models.BooleanField(default=False, verbose_name="show on dashboard"),
        ),
        migrations.AlterField(
            model_name="savedview",
            name="show_in_sidebar",
            field=models.BooleanField(default=False, verbose_name="show in sidebar"),
        ),
        migrations.RunPython(
            _set_default_visibility_ids,
            reverse_code=_restore_visibility_fields,
        ),
        migrations.RemoveField(
            model_name="savedview",
            name="show_on_dashboard",
        ),
        migrations.RemoveField(
            model_name="savedview",
            name="show_in_sidebar",
        ),
    ]
