<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections/{position}/apply-variant', method: 'POST',
            domain: 'content', resource: 'template-section', verb: 'apply-variant',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'position'         => ['type' => 'integer'],
                    'variantId'        => ['type' => 'string'],
                ],
                'required' => ['sourceTemplateId', 'position', 'variantId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['appliedVariantId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Apply a saved section variant\'s configuration to a runtime template section position.',
            sideEffects: ['updates runtime template schema sections[position] to match variant'],
            preconditions: ['runtime draft exists', 'position is valid', 'variantId exists'],
            postconditions: ['section position reflects variant configuration'],
            audienceClass: 4, adminAliases: ['apply-section-variant'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->applySectionVariant(
                (string) ($input['sourceTemplateId'] ?? ''),
                (int) ($input['position'] ?? -1),
                (string) ($input['variantId'] ?? ''),
                $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()); }
    }
}
