# retoor <retoor@molodetz.nl>

import logging

from fastapi import APIRouter, Request
from devplacepy.database import get_table
from devplacepy.database.awards import revoke_award
from devplacepy.responses import action_result, json_error, wants_json
from devplacepy.services.audit import record as audit
from devplacepy.utils import not_found, require_admin, safe_next

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


def _redirect_back(request: Request, award: dict) -> str:
    referer = request.headers.get("referer", "")
    if referer and safe_next(referer, "") == referer:
        return referer
    receiver = get_table("users").find_one(uid=award.get("receiver_uid", ""))
    if receiver:
        return f"/profile/{receiver['username']}?tab=awards"
    return "/admin"


@router.post("/awards/{uid}/revoke")
async def admin_revoke_award(request: Request, uid: str):
    admin = require_admin(request)
    row = revoke_award(uid, admin["uid"])
    if not row:
        if wants_json(request):
            return json_error(404, "Award not found")
        raise not_found("Award not found")
    receiver = get_table("users").find_one(uid=row.get("receiver_uid", ""))
    logger.info("Admin %s revoked award %s", admin["username"], uid)
    audit.record(
        request,
        "award.revoke",
        user=admin,
        target_type="award",
        target_uid=uid,
        target_label=row.get("slug", uid),
        summary=f"admin {admin['username']} revoked award {row.get('slug', uid)}",
        links=[
            audit.target("award", uid, row.get("slug")),
            audit.target("user", row.get("receiver_uid"), receiver.get("username") if receiver else None),
        ],
    )
    return action_result(request, _redirect_back(request, row))