<?php

declare(strict_types=1);

/** APO-197 Card 6 — POST /api/v1/administration/ai-connections/{integrationId}/rotate */
final class MyronRotateAiConnectionAction implements MyronAction
{
    public function __construct(private readonly MyronAiIntegrationRepository $repo) {}
    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/administration/ai-connections/{integrationId}/rotate', method: 'POST',
            domain: 'administration', resource: 'ai-connection', verb: 'rotate',
            inputSchema: [
                'type' => 'object',
                'properties' => ['integrationId' => ['type' => 'string']],
                'required' => ['integrationId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['rawToken' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::ADMINISTRATION_DESTRUCTIVE,
            summary: 'Rotate an AI integration\'s token. Returns the new raw token once; the old token stops working immediately.',
            sideEffects: ['updates ai_integrations.token_hash + token_prefix'], audienceClass: 4,
            adminAliases: ['rotate-ai-connection'],
            snapshotInclude: false, exposeToMcp: false,
        );
    }
    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $rotated = $this->repo->rotateToken((string) ($input['integrationId'] ?? ''));
            return MyronActionResult::ok(['rawToken' => $rotated['rawToken']]);
        } catch (InvalidArgumentException $e) { return MyronActionResult::error('input_invalid', $e->getMessage()); }
        catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
