<?php

declare(strict_types=1);

final class MyronCreateCustomJsUploadSessionAction 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-session',
            method: 'POST',
            domain: 'design',
            resource: 'custom-js-upload-session',
            verb: 'create',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sizeBytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                ],
                'required' => ['sizeBytes', 'sha256'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Create a chunked upload session for Custom Interactions JavaScript.',
            sideEffects: ['creates temporary upload session metadata'],
            preconditions: ['caller holds design.write'],
            postconditions: ['upload session accepts ordered JavaScript chunks'],
            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->begin(
                'design.customJs',
                'custom-interactions.js',
                'application/javascript',
                (int) ($input['sizeBytes'] ?? 0),
                (string) ($input['sha256'] ?? '')
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
