<?php

declare(strict_types=1);

/** APO-195 Card 2 — POST /api/v1/content/templates/{sourceTemplateId}/sections (insert-section) */
final class MyronInsertSectionAction implements MyronAction
{
    public function __construct(private readonly MyronSectionEditActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections', method: 'POST',
            domain: 'content', resource: 'template-section', verb: 'insert',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'sectionKey'       => ['type' => 'string'],
                    'insertAt'         => ['type' => 'integer'],
                ],
                'required' => ['sourceTemplateId', 'sectionKey'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['position' => ['type' => 'integer']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Insert a governed section into the runtime template draft at the given position.',
            sideEffects: ['updates runtime template schema sections array'],
            preconditions: ['runtime draft exists', 'sectionKey is governed and not a chrome/primitive-only key'],
            postconditions: ['section inserted at position'],
            audienceClass: 4, adminAliases: ['insert-section'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

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