# retoor <retoor@molodetz.nl>

from fastapi import Request
from fastapi.responses import RedirectResponse

from devplacepy.database import get_table
from devplacepy.responses import wants_json, json_error
from devplacepy.utils import require_user, not_found


def resolve_customization_target(request: Request, username: str):
    current_user = require_user(request)
    target = get_table("users").find_one(username=username)
    if not target:
        raise not_found("User not found")
    is_owner = current_user["uid"] == target["uid"]
    is_admin = current_user.get("role") == "Admin"
    if not (is_owner or is_admin):
        if wants_json(request):
            return None, json_error(403, "Not allowed")
        return None, RedirectResponse(url=f"/profile/{username}", status_code=302)
    return target, None
