# retoor <retoor@molodetz.nl>

import sys
from devplacepy.database import get_table, invalidate_admins_cache
from devplacepy.cli._shared import _audit_cli


def cmd_role_get(args):
    users = get_table("users")
    user = users.find_one(username=args.username)
    if not user:
        print(f"User '{args.username}' not found")
        sys.exit(1)
    print(user.get("role", "member").lower())


def cmd_role_set(args):
    role = args.role.lower()
    if role not in ("member", "admin"):
        print("Role must be 'member' or 'admin'")
        sys.exit(1)

    users = get_table("users")
    user = users.find_one(username=args.username)
    if not user:
        print(f"User '{args.username}' not found")
        sys.exit(1)

    old_role = user.get("role")
    users.update({"uid": user["uid"], "role": role.capitalize()}, ["uid"])
    invalidate_admins_cache()
    from devplacepy.services.audit import record as audit

    _audit_cli(
        "cli.role.set",
        f"CLI set role of user {args.username} from {old_role} to {role.capitalize()}",
        metadata={"old": old_role, "new": role.capitalize()},
        target_type="user",
        target_uid=user["uid"],
        target_label=args.username,
        links=[audit.target("user", user["uid"], args.username)],
    )
    print(f"User '{args.username}' role set to '{role}'")


def register_roles(subparsers):
    role = subparsers.add_parser("role", help="Manage user roles")
    role_sub = role.add_subparsers(title="action", dest="action")

    role_get = role_sub.add_parser("get", help="Get a user's role")
    role_get.add_argument("username")
    role_get.set_defaults(func=cmd_role_get)

    role_set = role_sub.add_parser("set", help="Set a user's role")
    role_set.add_argument("username")
    role_set.add_argument("role", choices=["member", "admin"])
    role_set.set_defaults(func=cmd_role_set)
