# retoor <retoor@molodetz.nl>

import logging
from typing import Annotated

from fastapi import Depends, APIRouter, Request

from devplacepy.models import InteractionsForm
from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit
from devplacepy.services.devii.interaction import prefs
from devplacepy.routers.profile._shared import resolve_customization_target
from devplacepy.dependencies import json_or_form

logger = logging.getLogger(__name__)
router = APIRouter()


@router.post("/{username}/interactions")
async def set_interactions(
    request: Request,
    username: str,
    data: Annotated[InteractionsForm, Depends(json_or_form(InteractionsForm))],
):
    target, denied = resolve_customization_target(request, username)
    if denied is not None:
        return denied
    if data.reset:
        snap = prefs.set_user_pref(target["uid"], None)
        summary = f"reset interactive widgets to admin default for {target['username']}"
        new_value = -1
    else:
        snap = prefs.set_user_pref(target["uid"], bool(data.enabled))
        summary = (
            f"{'enabled' if data.enabled else 'disabled'} interactive widgets "
            f"for {target['username']}"
        )
        new_value = 1 if data.enabled else 0
    logger.info(summary)
    audit.record(
        request,
        "profile.interactions",
        target_type="user",
        target_uid=target["uid"],
        target_label=target["username"],
        new_value=new_value,
        summary=summary,
        links=[audit.target("user", target["uid"], target["username"])],
    )
    url = f"/profile/{target['username']}"
    return action_result(
        request,
        url,
        data={
            "url": url,
            "enabled": snap["enabled"],
            "source": snap["source"],
            "default": snap["default"],
            "override": snap["override"],
        },
    )
