# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request

from devplacepy.avatar import avatar_url
from devplacepy.database import get_table
from devplacepy.responses import action_result
from devplacepy.utils import clear_user_cache, generate_uid
from devplacepy.services.audit import record as audit

from devplacepy.routers.profile._shared import resolve_customization_target

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


@router.post("/{username}/regenerate-avatar")
async def regenerate_avatar(request: Request, username: str):
    target, denied = resolve_customization_target(request, username)
    if denied is not None:
        return denied
    seed = generate_uid()
    get_table("users").update({"uid": target["uid"], "avatar_seed": seed}, ["uid"])
    clear_user_cache(target["uid"])
    logger.info(f"Avatar regenerated for {target['username']}")
    audit.record(
        request,
        "profile.avatar.regenerate",
        target_type="user",
        target_uid=target["uid"],
        target_label=target["username"],
        new_value=seed,
        summary=f"regenerated avatar for {target['username']}",
        links=[audit.target("user", target["uid"], target["username"])],
    )
    url = f"/profile/{target['username']}"
    return action_result(
        request,
        url,
        data={
            "url": url,
            "avatar_seed": seed,
            "avatar_url": avatar_url("multiavatar", seed, 80),
        },
    )
