<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/custom-interactions/fonts',
            method: 'PATCH',
            domain: 'design',
            resource: 'custom-interactions',
            verb: 'save-fonts',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'externalFonts' => ['type' => 'array'],
                    'uploadedFonts' => ['type' => 'array'],
                ],
                'required' => [],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'externalFonts' => ['type' => 'integer'],
                    'uploadedFonts' => ['type' => 'integer'],
                ],
            ],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary: 'Save site-wide Custom Interactions web font include settings.',
            sideEffects: ['writes custom_css_settings external_font_stylesheets and optionally uploaded_font_files records'],
            preconditions: ['external font stylesheet URLs are HTTPS when supplied'],
            postconditions: ['Custom Interactions font settings reflect the submitted values'],
            audienceClass: 4,
            adminAliases: ['save-custom-interaction-fonts'],
            snapshotInclude: false,
            exposeToMcp: true,
            mcpAltitude: 'last-resort',
            mcpPreferInstead: ['templates', 'registered sections', 'section variants', 'design tokens'],
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $externalFonts = is_array($input['externalFonts'] ?? null) ? array_values((array) $input['externalFonts']) : [];
            $uploadedFonts = array_key_exists('uploadedFonts', $input) && is_array($input['uploadedFonts'])
                ? array_values((array) $input['uploadedFonts'])
                : null;

            return MyronActionResult::ok($this->service->saveCustomInteractionFonts($externalFonts, $uploadedFonts, $caller));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
