# retoor <retoor@molodetz.nl>

import json

from fastapi import Request

from devplacepy.responses import action_result
from devplacepy.services.audit import record as audit


def seniority_key(user: dict) -> tuple[str, int]:
    return (user.get("created_at") or "", user.get("id") or 0)


def is_senior_admin(actor: dict, target: dict | None) -> bool:
    if not target or target.get("role") != "Admin":
        return False
    if target.get("uid") == actor.get("uid"):
        return False
    return seniority_key(target) < seniority_key(actor)


def deny_senior(
    request: Request,
    admin: dict,
    uid: str,
    target: dict,
    event_key: str,
    redirect_url: str = "/admin/users",
):
    audit.record(
        request,
        event_key,
        user=admin,
        result="denied",
        target_type="user",
        target_uid=uid,
        target_label=target.get("username"),
        summary=f"admin {admin['username']} cannot manage senior admin {target.get('username')}",
        links=[audit.target("user", uid, target.get("username"))],
    )
    return action_result(request, redirect_url)


def parse_metadata(raw: str | dict | None) -> dict | None:
    if not raw:
        return None
    if isinstance(raw, dict):
        return raw
    try:
        return json.loads(raw)
    except (ValueError, TypeError):
        return {"raw": str(raw)}
