<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections/{position}/duplicate',
            method: 'POST',
            domain: 'content',
            resource: 'template-section',
            verb: 'duplicate',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'position' => ['type' => 'integer'],
                    'insertAt' => ['type' => 'integer'],
                ],
                'required' => ['sourceTemplateId', 'position'],
            ],
            outputSchema: [
                'type' => 'object',
                'properties' => [
                    'position' => ['type' => 'integer'],
                    'newPosition' => ['type' => 'integer'],
                    'instanceKey' => ['type' => 'string'],
                ],
            ],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Duplicate a runtime-template section instance and insert the copy near the source section.',
            sideEffects: ['updates runtime template schema sections array and default section content'],
            preconditions: ['runtime draft exists', 'position is valid'],
            postconditions: ['section instance duplicated with unique instance identity'],
            audienceClass: 4,
            adminAliases: ['duplicate-section'],
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

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