<?php

declare(strict_types=1);

/** APO-195 Card 2 — PATCH .../default-content (update-template-section-content) */
final class MyronUpdateTemplateSectionContentAction implements MyronAction
{
    public function __construct(private readonly MyronSectionEditActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/default-content', method: 'PATCH',
            domain: 'content', resource: 'template-content', verb: 'update',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'content'          => ['type' => 'object'],
                ],
                'required' => ['sourceTemplateId', 'content'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['sectionsUpdated' => ['type' => 'integer']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Update the runtime template\'s defaultContent map (section-key keyed content fields).',
            sideEffects: ['updates page_template_versions.schema_json.defaultContent'],
            preconditions: ['runtime draft exists'],
            postconditions: ['defaultContent reflects input'],
            audienceClass: 4, adminAliases: ['update-template-section-content'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

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