<?php

declare(strict_types=1);

/** APO-195 Card 2 — POST .../sections/{position}/save-as-variant (save-section-variant) */
final class MyronSaveSectionAsVariantAction implements MyronAction
{
    public function __construct(private readonly MyronSectionEditActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections/{position}/save-as-variant', method: 'POST',
            domain: 'content', resource: 'template-section', verb: 'save-as-variant',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'position'         => ['type' => 'integer'],
                    'variantName'      => ['type' => 'string'],
                ],
                'required' => ['sourceTemplateId', 'position', 'variantName'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['variantId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Save a runtime template section\'s current state as a reusable saved section variant.',
            sideEffects: ['inserts section_variants row'],
            preconditions: ['runtime draft exists', 'position is valid', 'variantName is non-empty'],
            postconditions: ['section variant exists; applicable across pages'],
            audienceClass: 4, adminAliases: ['save-section-variant'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->saveSectionAsVariant(
                (string) ($input['sourceTemplateId'] ?? ''),
                (int) ($input['position'] ?? -1),
                (string) ($input['variantName'] ?? ''),
                $caller
            ));
        } catch (MyronActionPreconditionError $e) { return MyronActionResult::error('precondition_failed', $e->getMessage()); }
        catch (InvalidArgumentException $e) { return MyronActionResult::error('input_invalid', $e->getMessage()); }
        catch (Throwable $e) { return MyronActionResult::error('business_rule_failed', $e->getMessage()); }
    }
}
