<?php

declare(strict_types=1);

final class MyronSetPageBodyMarkdownAction implements MyronAction
{
    public function __construct(private readonly MyronPageContractService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/pages/{pageId}/body-markdown',
            method: 'PATCH',
            domain: 'content',
            resource: 'page-body',
            verb: 'set-markdown',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'pageId' => ['type' => 'string'],
                    'sectionInstanceKey' => ['type' => 'string'],
                    'markdown' => ['type' => 'string'],
                    'bodyMarkdown' => ['type' => 'string'],
                    'publish' => ['type' => 'boolean'],
                    'publishedAt' => ['type' => 'string'],
                ],
                'required' => ['pageId'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['pageId' => ['type' => 'string'], 'sectionInstanceKey' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Convert Markdown to governed rich text HTML and store it in an editable Page Contract body field.',
            sideEffects: ['inserts new page_versions row', 'updates pages.current_draft_version_id', 'optionally publishes page'],
            preconditions: ['page exists', 'target section has an editable body field'],
            postconditions: ['Markdown body renders as sanitized long-form post HTML'],
            audienceClass: 4,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            $markdown = array_key_exists('markdown', $input) ? (string) $input['markdown'] : (string) ($input['bodyMarkdown'] ?? '');
            return MyronActionResult::ok($this->service->updateBodyMarkdown(
                (string) ($input['pageId'] ?? ''),
                isset($input['sectionInstanceKey']) ? (string) $input['sectionInstanceKey'] : null,
                $markdown,
                (bool) ($input['publish'] ?? false),
                isset($input['publishedAt']) ? (string) $input['publishedAt'] : null
            ));
        } 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());
        }
    }
}
