<?php

declare(strict_types=1);

/** APO-197 Card 5 — POST /api/v1/administration/ai-connections (exposeToMcp:false; AI cannot manage its own integrations) */
final class MyronCreateAiConnectionAction implements MyronAction
{
    public function __construct(private readonly MyronAiIntegrationRepository $repo) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/ai-connections', method: 'POST',
            domain: 'administration', resource: 'ai-connection', verb: 'create',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'label' => ['type' => 'string'],
                    'scopes' => ['type' => 'array'],
                    'rateLimitConfig' => ['type' => 'object'],
                ],
                'required' => ['label', 'scopes'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['integrationId' => ['type' => 'string'], 'rawToken' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_WRITE,
            summary: 'Create a new AI integration. Returns raw token ONCE; operator-only.',
            sideEffects: ['inserts ai_integrations row'], audienceClass: 4,
            adminAliases: ['create-ai-connection'],
            snapshotInclude: false, exposeToMcp: false,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $scopes = is_array($input['scopes'] ?? null) ? array_map('strval', $input['scopes']) : [];
            $rateConfig = is_array($input['rateLimitConfig'] ?? null) ? $input['rateLimitConfig'] : null;
            $userId = $caller->callerType === 'human-session' ? $caller->callerId : '';
            $created = $this->repo->create((string) ($input['label'] ?? ''), $scopes, $userId, $rateConfig);
            return MyronActionResult::ok([
                'integrationId' => $created['integration']->id,
                'rawToken'      => $created['rawToken'],
            ]);
        } catch (InvalidArgumentException $e) { return MyronActionResult::error('input_invalid', $e->getMessage()); }
        catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
