<?php

declare(strict_types=1);

/** APO-249 — POST /api/v1/administration/users/{userId}/role */
final class MyronUpdateUserRoleAction implements MyronAction
{
    public function __construct(private readonly MyronIdentityActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/users/{userId}/role',
            method: 'POST',
            domain: 'administration',
            resource: 'user-role',
            verb: 'update',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'userId' => ['type' => 'string'],
                    'role_key' => ['type' => 'string'],
                ],
                'required' => ['userId', 'role_key'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'user_id' => ['type' => 'string'],
                    'role_id' => ['type' => 'string'],
                    'role_key' => ['type' => 'string'],
                    'granted_scopes' => ['type' => 'array'],
                ],
            ],
            requiredScope: MyronApiScopes::ADMINISTRATION_DESTRUCTIVE,
            summary: 'Assign a role template and reset the user scope set to that template.',
            sideEffects: ['updates users.role_id', 'updates users.granted_scopes_json'],
            preconditions: ['user exists; role exists; caller holds every role-template scope'],
            postconditions: ['role and granted scopes match the selected template'],
            audienceClass: 4,
            adminAliases: ['save-role'],
            snapshotInclude: false,
            exposeToMcp: true
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->updateUserRole(
                (string) ($input['userId'] ?? ''),
                (string) ($input['role_key'] ?? ''),
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
