<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections/{position}/move', method: 'POST',
            domain: 'content', resource: 'template-section', verb: 'move',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'position'         => ['type' => 'integer'],
                    'direction'        => ['type' => 'string'],
                ],
                'required' => ['sourceTemplateId', 'position', 'direction'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['newPosition' => ['type' => 'integer']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Move a runtime-template section up or down by one position.',
            sideEffects: ['updates runtime template schema sections array'],
            preconditions: ['runtime draft exists', 'position is valid'],
            postconditions: ['section position swapped with neighbour'],
            audienceClass: 4, adminAliases: ['move-section'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

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