<?php

declare(strict_types=1);

/**
 * APO-193 Card 6 — Save the site-wide custom CSS layer.
 *
 * URI:   PATCH /api/v1/design/custom-css/site
 * Scope: design.write
 */
final class MyronSaveSiteCustomCssAction implements MyronAction
{
    public function __construct(
        private readonly MyronCustomCssActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/custom-css/site',
            method:        'PATCH',
            domain:        'design',
            resource:      'custom-css',
            verb:          'save-site',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'css' => ['type' => 'string'],
                ],
                'required'   => ['css'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => ['bytes' => ['type' => 'integer']],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Save the site-wide custom CSS layer. Emitted after runtime tokens and public component CSS; overrides nothing implicitly — operator authored.',
            sideEffects:     ['writes custom_css_settings (scope_type=site)'],
            preconditions:   [],
            postconditions:  ['site custom CSS layer reflects the input string'],
            audienceClass:   4,
            adminAliases:    ['save-site-custom-css'],
            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->service->saveSiteCss(
                (string) ($input['css'] ?? ''),
                $caller
            ));
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
