<?php

declare(strict_types=1);

/** APO-412 — POST /api/v1/content/templates/{sourceTemplateId}/sections/reorder */
final class MyronReorderTemplateSectionsAction implements MyronAction
{
    public function __construct(private readonly MyronSectionEditActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections/reorder',
            method: 'POST',
            domain: 'content',
            resource: 'template-section',
            verb: 'reorder',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'positions' => [
                        'type' => 'array',
                        'items' => ['type' => 'integer'],
                    ],
                ],
                'required' => ['sourceTemplateId', 'positions'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'positions' => ['type' => 'array'],
                ],
            ],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Persist an arbitrary runtime-template section order after validated drag/drop reordering.',
            sideEffects: ['updates runtime template schema sections array'],
            preconditions: ['runtime draft exists', 'positions include every section exactly once'],
            postconditions: ['section order persisted without losing section instance identity'],
            audienceClass: 4,
            adminAliases: ['reorder-sections'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $positions = is_array($input['positions'] ?? null) ? array_values(array_map('intval', $input['positions'])) : [];
            return MyronActionResult::ok($this->service->reorderSections(
                (string) ($input['sourceTemplateId'] ?? ''),
                $positions,
                $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());
        }
    }
}
