# retoor <retoor@molodetz.nl>

import logging
from typing import Annotated
from fastapi import Depends, APIRouter, Request
from devplacepy.models import CustomizationToggleForm
from devplacepy.database import set_customization_pref
from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit

from devplacepy.routers.profile._shared import resolve_customization_target
from devplacepy.dependencies import json_or_form

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

def _toggle_customization(
    request: Request, username: str, category: str, value: bool
):
    target, denied = resolve_customization_target(request, username)
    if denied is not None:
        return denied
    set_customization_pref(target["uid"], category, disabled=not value)
    column = "cust_disable_global" if category == "global" else "cust_disable_pagetype"
    logger.info(
        f"Customization {category} {'enabled' if value else 'disabled'} for {target['username']}"
    )
    audit.record(
        request,
        f"profile.customization.{category}.toggle",
        target_type="user",
        target_uid=target["uid"],
        target_label=target["username"],
        old_value=0 if value else 1,
        new_value=1 if value else 0,
        summary=f"{'enabled' if value else 'disabled'} {category} customizations for {target['username']}",
        links=[audit.target("user", target["uid"], target["username"])],
    )
    url = f"/profile/{target['username']}"
    return action_result(request, url, data={"url": url, column: not value})

@router.post("/{username}/customization/global")
async def set_customization_global(
    request: Request,
    username: str,
    data: Annotated[CustomizationToggleForm, Depends(json_or_form(CustomizationToggleForm))],
):
    return _toggle_customization(request, username, "global", data.value)

@router.post("/{username}/customization/pagetype")
async def set_customization_pagetype(
    request: Request,
    username: str,
    data: Annotated[CustomizationToggleForm, Depends(json_or_form(CustomizationToggleForm))],
):
    return _toggle_customization(request, username, "pagetype", data.value)
