"""Users create command implementation."""

from typing import Optional

import typer

from cli.commands.users.create.presenter import present_create_result
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.users import CreateUserRequest
from alloy_runtime_types.enums.member_role import MemberRole


def users_create_command(
    email: str = typer.Option(
        ...,
        "-e",
        "--email",
        help="User email address",
    ),
    name: str = typer.Option(
        ...,
        "-n",
        "--name",
        help="User display name",
    ),
    role: Optional[str] = typer.Option(
        None,
        "-r",
        "--role",
        help="User role (member, admin, owner). Defaults to member",
    ),
) -> None:
    """Create a new user.

    Examples:
        alloy users create --email user@example.com --name "John Doe"
        alloy users create -e admin@example.com -n "Admin User" -r admin
    """
    role_enum = MemberRole(role.lower()) if role else MemberRole.MEMBER
    _execute_create(email=email, name=name, role=role_enum)


@async_command
async def _execute_create(
    email: str,
    name: str,
    role: MemberRole,
) -> None:
    request = CreateUserRequest(email=email, name=name, role_id=role)
    async with authenticated_client() as (_config, client):
        response = await client.create_user(request)

    present_create_result(response)
