<?php

declare(strict_types=1);

/** APO-249 — PATCH /api/v1/administration/users/{userId}/scopes */
final class MyronUpdateUserScopesAction implements MyronAction
{
    public function __construct(private readonly MyronIdentityActionService $service) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/users/{userId}/scopes', method: 'PATCH',
            domain: 'administration', resource: 'user-scopes', verb: 'update',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'userId' => ['type' => 'string'],
                    'granted_scopes' => ['type' => 'array', 'items' => ['type' => 'string']],
                ],
                'required' => ['userId', 'granted_scopes'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'user_id' => ['type' => 'string'],
                    'prior_scopes' => ['type' => 'array'],
                    'granted_scopes' => ['type' => 'array'],
                    'role_id' => ['type' => 'string'],
                ],
            ],
            requiredScope: MyronApiScopes::ADMINISTRATION_DESTRUCTIVE,
            summary: 'Update a user scope set with privilege-escalation protection.',
            sideEffects: ['updates users.granted_scopes_json'],
            preconditions: ['user exists; caller holds every granted scope'],
            postconditions: ['users.granted_scopes_json reflects input'],
            audienceClass: 4, adminAliases: ['save-scopes'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->updateUserScopes(
                (string) ($input['userId'] ?? ''),
                is_array($input['granted_scopes'] ?? null) ? $input['granted_scopes'] : [],
                $caller
            ));
        } catch (InvalidArgumentException $e) { return MyronActionResult::error('input_invalid', $e->getMessage()); }
        catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
