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()}
    applets = {a.slug: a for a in Applet.objects.filter(context=context)}
    return [
        {"applet": applets[slug], "visible": ua_map.get(applets[slug].pk, applets[slug].default_visible)}
        for slug in applets
        if slug in applets
    ]
