<?php

declare(strict_types=1);

final class MyronCommitCustomJsUploadSessionAction implements MyronAction
{
    public function __construct(
        private readonly MyronUploadSessionService $sessions,
        private readonly MyronCustomCssActionService $service,
        private readonly MyronCustomCssRepository $repository,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-interactions/site/custom-js/upload-sessions/{sessionId}/commit',
            method: 'POST',
            domain: 'design',
            resource: 'custom-js-upload-session',
            verb: 'commit',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sessionId' => ['type' => 'string'],
                ],
                'required' => ['sessionId'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Commit a completed Custom Interactions JavaScript upload session.',
            sideEffects: ['writes custom_css_settings site custom_js record', 'deletes temporary session'],
            preconditions: ['session is complete', 'session sha256 matches payload'],
            postconditions: ['customJs reflects uploaded bytes'],
            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
    {
        $sessionId = (string) ($input['sessionId'] ?? '');
        try {
            $complete = $this->sessions->complete($sessionId, 'design.customJs', true);
            $state = $this->repository->customInteractions();
            $externalLibraries = is_array($state['externalLibraries'] ?? null) ? array_values((array) $state['externalLibraries']) : [];
            $result = $this->service->saveCustomInteractions($externalLibraries, $complete['bytes'], $caller);
            $this->sessions->cleanup($sessionId);
            return MyronActionResult::ok($result);
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
