from database import fetch_one


ROLE_LEVELS = {
    "member": 1,
    "admin": 2,
    "owner": 3,
}


def get_role(room_id: int, user_id: int) -> int | None:
    member = fetch_one(
        """
        SELECT role
        FROM room_members
        WHERE room_id = ?
        AND user_id = ?
        """,
        (room_id, user_id),
    )

    if member is None:
        return None

    role_levels = {
        "member": 1,
        "admin": 2,
        "owner": 3,
    }

    return role_levels.get(member["role"])


def has_role(
    room_id: int,
    user_id: int,
    required_role: str,
) -> bool:
    """
    Check whether a user has at least the required role.

    Role hierarchy:
        owner > admin > member
    """
    user_role = get_role(room_id, user_id)

    if user_role is None:
        return False

    user_level = ROLE_LEVELS.get(user_role, 0)
    required_level = ROLE_LEVELS.get(required_role, 0)

    if required_level == 0:
        return False

    return user_level >= required_level


def whoami(room_id: int, user_id: int) -> dict:
    """
    Return the user's permissions within a room.
    """
    role = get_role(room_id, user_id)

    if role is None:
        return {
            "member": False,
            "role": None,
            "is_admin": False,
            "is_owner": False,
        }

    return {
        "member": True,
        "role": role,
        "is_admin": ROLE_LEVELS.get(role, 0) >= ROLE_LEVELS["admin"],
        "is_owner": role == "owner",
    }


# PUBLIC
# ├── POST /create-user
# ├── POST /login
# ├── GET  /
# └── GET  /ascii-art

# AUTHENTICATED
# ├── GET  /me
# ├── GET  /users/{id}
# ├── GET  /database
# ├── POST /create-room
# ├── POST /search-room
# ├── POST /join-room
# └── GET  /rooms

# MEMBER
# ├── GET    /rooms/{id}
# ├── GET    /rooms/{id}/whoami
# ├── GET    /rooms/{id}/members
# ├── GET    /rooms/{id}/events
# ├── DELETE /rooms/{id}/members/me
# ├── POST   /events
# ├── GET    /events
# ├── GET    /events/{id}
# ├── POST   /events/{id}/respond
# └── GET    /events/{id}/responses

# ADMIN
# ├── PATCH  /rooms/{id}
# ├── POST   /rooms/{id}/invite-code
# ├── PATCH  /events/{id}
# └── DELETE /events/{id}

# OWNER
# └── DELETE /rooms/{id}