<?php

declare(strict_types=1);

/** APO-195 Card 2 — PATCH .../sections/{position}/editability (update-section-editability) */
final class MyronUpdateSectionEditabilityAction implements MyronAction
{
    public function __construct(private readonly MyronSectionEditActionService $service) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/content/templates/{sourceTemplateId}/sections/{position}/editability', method: 'PATCH',
            domain: 'content', resource: 'template-section', verb: 'update-editability',
            inputSchema: [
                'type' => 'object',
                'properties' => [
                    'sourceTemplateId' => ['type' => 'string'],
                    'position'         => ['type' => 'integer'],
                    'contentEditable'  => ['type' => 'boolean'],
                ],
                'required' => ['sourceTemplateId', 'position', 'contentEditable'],
            ],
            outputSchema: ['type' => 'object', 'properties' => ['contentEditable' => ['type' => 'boolean']]],
            requiredScope: MyronApiScopes::CONTENT_WRITE,
            summary: 'Update a section\'s contentEditable flag in the runtime template draft.',
            sideEffects: ['updates runtime template schema sections[position].editing.contentEditable'],
            preconditions: ['runtime draft exists', 'position is valid'],
            postconditions: ['section editability reflects input'],
            audienceClass: 4, adminAliases: ['update-section-editability'],
            snapshotInclude: false, exposeToMcp: true,
        );
    }

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