# retoor <retoor@molodetz.nl>

import logging
from fastapi import APIRouter, Request
from devplacepy.database import get_table, _now_iso, invalidate_user_relations
from devplacepy.utils import generate_uid, require_user
from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit

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


def _toggle_on(request, username, kind, audit_key, verb):
    user = require_user(request)
    target = get_table("users").find_one(username=username)
    if not target or target["uid"] == user["uid"]:
        return action_result(request, f"/profile/{username}")

    relations = get_table("user_relations")
    existing = relations.find_one(
        user_uid=user["uid"], target_uid=target["uid"], kind=kind
    )
    if existing and not existing.get("deleted_at"):
        return action_result(request, f"/profile/{username}")
    if existing:
        relations.update(
            {"id": existing["id"], "deleted_at": None, "deleted_by": None}, ["id"]
        )
    else:
        relations.insert(
            {
                "uid": generate_uid(),
                "user_uid": user["uid"],
                "target_uid": target["uid"],
                "kind": kind,
                "created_at": _now_iso(),
                "deleted_at": None,
                "deleted_by": None,
            }
        )
    invalidate_user_relations(user["uid"])
    logger.info(f"{user['username']} {verb} {username}")
    audit.record(
        request,
        audit_key,
        user=user,
        target_type="user",
        target_uid=target["uid"],
        target_label=username,
        summary=f"{user['username']} {verb} {username}",
        links=[audit.target("user", target["uid"], username)],
    )
    return action_result(request, f"/profile/{username}")


def _toggle_off(request, username, kind, audit_key, verb):
    user = require_user(request)
    target = get_table("users").find_one(username=username)
    if not target:
        return action_result(request, f"/profile/{username}")

    relations = get_table("user_relations")
    existing = relations.find_one(
        user_uid=user["uid"], target_uid=target["uid"], kind=kind, deleted_at=None
    )
    if existing:
        relations.update(
            {"id": existing["id"], "deleted_at": _now_iso(), "deleted_by": user["uid"]},
            ["id"],
        )
        invalidate_user_relations(user["uid"])
        logger.info(f"{user['username']} {verb} {username}")
        audit.record(
            request,
            audit_key,
            user=user,
            target_type="user",
            target_uid=target["uid"],
            target_label=username,
            summary=f"{user['username']} {verb} {username}",
            links=[audit.target("user", target["uid"], username)],
        )
    return action_result(request, f"/profile/{username}")


@router.post("/block/unblock/{username}")
async def unblock_user(request: Request, username: str):
    return _toggle_off(request, username, "block", "relation.unblock", "unblocked")


@router.post("/block/{username}")
async def block_user(request: Request, username: str):
    return _toggle_on(request, username, "block", "relation.block", "blocked")


@router.post("/mute/unmute/{username}")
async def unmute_user(request: Request, username: str):
    return _toggle_off(request, username, "mute", "relation.unmute", "unmuted")


@router.post("/mute/{username}")
async def mute_user(request: Request, username: str):
    return _toggle_on(request, username, "mute", "relation.mute", "muted")
