<?php

declare(strict_types=1);

/** APO-349 — POST /api/v1/design/custom-interactions/libraries */
final class MyronUploadCustomInteractionLibraryAction implements MyronAction
{
    public function __construct(private readonly MyronCustomCssActionService $service)
    {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-interactions/libraries',
            method: 'POST',
            domain: 'design',
            resource: 'custom-interactions',
            verb: 'upload-library',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'filename' => ['type' => 'string'],
                    'contentType' => ['type' => 'string'],
                    'contentBase64' => ['type' => 'string'],
                    'sizeBytes' => ['type' => 'integer'],
                    'sha256' => ['type' => 'string'],
                    'label' => ['type' => 'string'],
                ],
                'required' => ['filename', 'contentType', 'contentBase64', 'sizeBytes', 'sha256'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'id' => ['type' => 'string'],
                    'name' => ['type' => 'string'],
                    'url' => ['type' => 'string'],
                    'sha256' => ['type' => 'string'],
                    'sizeBytes' => ['type' => 'integer'],
                ],
            ],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Upload a site-wide Custom Interactions JavaScript library using the canonical JSON-content envelope.',
            sideEffects: ['writes bytes to app/uploads/interactions', 'updates custom_css_settings uploaded_js_libraries record'],
            preconditions: ['filename ends in .js', 'sha256 matches decoded bytes', 'payload is 1 MB or smaller'],
            postconditions: ['uploaded library has a deterministic MyronCMS-hosted script URL'],
            audienceClass: 4,
            adminAliases: ['upload-custom-interaction-library'],
            snapshotInclude: false,
            exposeToMcp: true,
            mcpAltitude: 'last-resort',
            mcpPreferInstead: ['templates', 'registered sections', 'section variants', 'design tokens'],
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $envelope = [
                'filename' => $input['filename'] ?? '',
                'contentType' => $input['contentType'] ?? '',
                'contentBase64' => $input['contentBase64'] ?? '',
                'sizeBytes' => $input['sizeBytes'] ?? 0,
                'sha256' => $input['sha256'] ?? '',
            ];
            return MyronActionResult::ok($this->service->uploadInteractionLibraryFromEnvelope(
                $envelope,
                (string) ($input['label'] ?? ''),
                $caller
            ));
        } catch (MyronJsonContentEnvelopeError $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
