from apps.applets.models import Applet, UserApplet


def apply_applet_toggle(user, context, checked_slugs):
    """Persist applet visibility choices for a given context."""
    for applet in Applet.objects.filter(context=context):
        UserApplet.objects.update_or_create(
            user=user,
            applet=applet,
            defaults={"visible": applet.slug in checked_slugs},
        )


def applet_context(user, context):
    ua_map = {ua.applet_id: ua.visible for ua in user.user_applets.all()}
    # `display_order` (lower = earlier) is the primary sort key; `pk` tie-breaks
    # so applets at the default order=100 keep their historical insertion-order
    # rendering. New applets that want pinned positions set order < 100 in
    # their seed migration (eg. wallet-shop = 10 to render atop the wallet row).
    applets_qs = Applet.objects.filter(context=context).order_by("display_order", "pk")
    return [
        {"applet": a, "visible": ua_map.get(a.pk, a.default_visible)}
        for a in applets_qs
    ]
