<?php

declare(strict_types=1);

final class MyronAppendCustomJsUploadChunkAction implements MyronAction
{
    public function __construct(private readonly MyronUploadSessionService $sessions)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-interactions/site/custom-js/upload-sessions/{sessionId}/chunks',
            method: 'PATCH',
            domain: 'design',
            resource: 'custom-js-upload-session-chunk',
            verb: 'append',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sessionId' => ['type' => 'string'],
                    'offset' => ['type' => 'integer'],
                    'contentBase64' => ['type' => 'string'],
                    'sha256' => ['type' => 'string'],
                ],
                'required' => ['sessionId', 'offset', 'contentBase64'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Append one base64 chunk to a Custom Interactions JavaScript upload session.',
            sideEffects: ['appends temporary JavaScript bytes'],
            preconditions: ['session exists', 'offset matches receivedBytes'],
            postconditions: ['session receivedBytes advances by chunk length'],
            audienceClass: 4,
            adminAliases: [],
            snapshotInclude: false,
            exposeToMcp: true,
            mcpAltitude: 'last-resort',
            mcpPreferInstead: ['templates', 'registered sections', 'section variants', 'design tokens'],
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->sessions->append(
                (string) ($input['sessionId'] ?? ''),
                'design.customJs',
                (int) ($input['offset'] ?? 0),
                (string) ($input['contentBase64'] ?? ''),
                (string) ($input['sha256'] ?? '')
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
