<?php

declare(strict_types=1);

/** APO-195 Card 2 — POST /api/v1/content/templates/{sourceTemplateId}/draft (create-runtime-draft) */
final class MyronCreateRuntimeDraftAction implements MyronAction
{
    public function __construct(private readonly MyronSectionEditActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/draft', method: 'POST',
            domain: 'content', resource: 'template-draft', verb: 'create',
            inputSchema: ['type' => 'object', 'properties' => ['sourceTemplateId' => ['type' => 'string']], 'required' => ['sourceTemplateId']],
            outputSchema: ['type' => 'object', 'properties' => ['runtimeTemplateId' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Create or resolve an editable runtime template target from a packaged definition or Custom Site Template.',
            sideEffects: ['inserts runtime_template row from definition when no editable custom template target exists'],
            preconditions: ['source template definition exists or Custom Site Template exists'],
            postconditions: ['runtime template target exists and is editable'],
            audienceClass: 4, adminAliases: ['create-runtime-draft'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

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