<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-interactions/site',
            method: 'PATCH',
            domain: 'design',
            resource: 'custom-interactions',
            verb: 'save-site',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'externalLibraries' => ['type' => 'array'],
                    'customJs' => ['type' => 'string'],
                ],
                'required' => [],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'externalLibraries' => ['type' => 'integer'],
                    'uploadedLibraries' => ['type' => 'integer'],
                    'customJsBytes' => ['type' => 'integer'],
                ],
            ],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Save site-wide Custom Interactions JS settings without changing the compatible Custom CSS endpoint.',
            sideEffects: ['writes custom_css_settings site creative_deps and custom_js records'],
            preconditions: ['external library URLs are HTTPS when supplied'],
            postconditions: ['Custom Interactions JS settings reflect the submitted values'],
            audienceClass: 4,
            adminAliases: ['save-custom-interactions-js'],
            snapshotInclude: false,
            exposeToMcp: true,
            mcpAltitude: 'last-resort',
            mcpPreferInstead: ['templates', 'registered sections', 'section variants', 'design tokens'],
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $externalLibraries = is_array($input['externalLibraries'] ?? null) ? array_values((array) $input['externalLibraries']) : [];
            return MyronActionResult::ok($this->service->saveCustomInteractions(
                $externalLibraries,
                (string) ($input['customJs'] ?? ''),
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
