<?php

declare(strict_types=1);

/** APO-197 Card 6 — PATCH /api/v1/administration/ai-connections/{integrationId} */
final class MyronUpdateAiConnectionAction implements MyronAction
{
    public function __construct(private readonly MyronAiIntegrationRepository $repo) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/ai-connections/{integrationId}', method: 'PATCH',
            domain: 'administration', resource: 'ai-connection', verb: 'update',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'integrationId'   => ['type' => 'string'],
                    'label'           => ['type' => 'string'],
                    'scopes'          => ['type' => 'array'],
                    'rateLimitConfig' => ['type' => 'object'],
                ],
                'required' => ['integrationId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['integrationId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Update an AI integration\'s label, scopes, or rate-limit config. Operator-only.',
            sideEffects: ['updates ai_integrations row'], audienceClass: 4,
            adminAliases: ['update-ai-connection'],
            snapshotInclude: false, exposeToMcp: false,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('mcp.site_operations');
        if ($entitlement !== null) {
            return $entitlement;
        }
        try {
            $scopes = is_array($input['scopes'] ?? null) ? array_map('strval', $input['scopes']) : [];
            $rateConfig = is_array($input['rateLimitConfig'] ?? null) ? $input['rateLimitConfig'] : null;
            $this->repo->updateMetadata((string) ($input['integrationId'] ?? ''), (string) ($input['label'] ?? ''), $scopes, $rateConfig);
            return MyronActionResult::ok(['integrationId' => (string) ($input['integrationId'] ?? '')]);
        } catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }

    private function requireCapability(string $capability): ?MyronActionResult
    {
        if (!function_exists('myronEntitlementGate')) {
            return null;
        }
        try {
            $decision = myronEntitlementGate()->evaluate($capability);
        } catch (Throwable) {
            return MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
        }
        return in_array((string) ($decision['outcome'] ?? ''), ['allowed', 'warn'], true)
            ? null
            : MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
    }
}
