<?php

declare(strict_types=1);

/** APO-196 Card 5 — PATCH /api/v1/administration/users/{userId}/password (exposeToMcp:false; credential material) */
final class MyronUpdatePasswordAction implements MyronAction
{
    public function __construct(private readonly MyronIdentityActionService $service) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/users/{userId}/password', method: 'PATCH',
            domain: 'administration', resource: 'user-password', verb: 'update',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'userId'       => ['type' => 'string'],
                    'password'     => ['type' => 'string'],
                    'confirmation' => ['type' => 'string'],
                ],
                'required' => ['userId', 'password', 'confirmation'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['userId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Update a user password. exposeToMcp:false — credential material; operator-only.',
            sideEffects: ['updates users.password_hash'],
            preconditions: ['user exists', 'password matches confirmation'],
            postconditions: ['password updated; existing sessions remain valid until next auth check'],
            audienceClass: 4, adminAliases: ['save-password'],
            snapshotInclude: false, exposeToMcp: false,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->updatePassword(
                (string) ($input['userId'] ?? ''),
                (string) ($input['password'] ?? ''),
                (string) ($input['confirmation'] ?? ''),
                $caller
            ));
        } catch (InvalidArgumentException $e) { return MyronActionResult::error('input_invalid', $e->getMessage()); }
        catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
