"""Credential update command implementation."""

from typing import Optional
from uuid import UUID

import typer

from cli.commands.credentials.update.presenter import present_credential_update_success
from cli.commands.shared_flags import (
    CREDENTIAL_VALUE_OPTIONAL,
    DESCRIPTION,
    NAME_OPTIONAL,
)
from cli.infrastructure.command import async_command, authenticated_client
from alloy_runtime_types.dtos.credentials import UpdateCredentialRequest


def credentials_update_command(
    credential_id: UUID = typer.Argument(..., help="Credential UUID"),
    name: Optional[str] = NAME_OPTIONAL,
    description: Optional[str] = DESCRIPTION,
    value: Optional[str] = CREDENTIAL_VALUE_OPTIONAL,
) -> None:
    """Update a credential (system or organization).

    At least one flag required.

    Examples:

        alloy credentials update <uuid> -n "Production Key"
        alloy credentials update <uuid> -d "Updated" --value "sk_new"
    """
    _execute_update(credential_id, name, description, value)


@async_command
async def _execute_update(
    credential_id: UUID,
    name: Optional[str],
    description: Optional[str],
    value: Optional[str],
) -> None:
    """Execute the credential update operation."""
    request = UpdateCredentialRequest(
        name=name,
        description=description,
        secret=value,
    )

    async with authenticated_client() as (_config, client):
        response = await client.update_credential(credential_id, request)

    present_credential_update_success(response)
