<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-css/site/upload-sessions/{sessionId}/commit',
            method: 'POST',
            domain: 'design',
            resource: 'custom-css-upload-session',
            verb: 'commit',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sessionId' => ['type' => 'string'],
                ],
                'required' => ['sessionId'],
            ],
            outputSchema: ['type' => 'object'],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Commit a completed site custom CSS upload session.',
            sideEffects: ['writes custom_css_settings site custom CSS record', 'deletes temporary session'],
            preconditions: ['session is complete', 'session sha256 matches payload'],
            postconditions: ['site custom CSS 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.siteCustomCss', true);
            $result = $this->service->saveSiteCss($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());
        }
    }
}
