<?php

declare(strict_types=1);

/**
 * APO-224 — Duplicate a packaged Site Template into an operator-owned Custom Site Template.
 *
 * URI:   POST /api/v1/design/templates/duplicate
 * Scope: design.write
 *
 * The admin form path in design/site-type-studio.php and this API path share
 * MyronTemplateDuplicationActionService::duplicate. The service requires a
 * schema resolver provided at construction time — the admin path's resolver
 * closure handles definition-to-schema translation; the API path uses a
 * substrate-equivalent resolver bound in bootstrap.
 */
final class MyronDuplicateTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronTemplateDuplicationActionService $service,
        private readonly MyronTemplateDefinitionRepository $templates,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/templates/duplicate',
            method:        'POST',
            domain:        'design',
            resource:      'template',
            verb:          'duplicate',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'name'             => ['type' => 'string'],
                ],
                'required'   => ['sourceTemplateId', 'name'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id'                 => ['type' => 'string'],
                    'source_template_id' => ['type' => 'string'],
                    'lifecycle'          => ['type' => 'object'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Duplicate a packaged Site Template into an operator-owned Custom Site Template; it is not available as a Page Template until registered.',
            sideEffects:     ['inserts page_templates row', 'inserts page_template_versions row'],
            preconditions:   ['source template exists and is registered'],
            postconditions:  ['new Custom Site Template row + initial version exist; ready for governed architectural editing'],
            audienceClass:   4,
            adminAliases:    ['duplicate-template'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $sourceId = (string) ($input['sourceTemplateId'] ?? '');
            $definition = $this->templates->findTemplateById($sourceId);
            if (!is_array($definition)) {
                return MyronActionResult::error('precondition_failed', 'Source template not found: ' . $sourceId);
            }
            return MyronActionResult::ok($this->service->duplicate(
                $definition,
                (string) ($input['name'] ?? ''),
                $caller
            ));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
