<?php

declare(strict_types=1);

/**
 * APO-231 — Update an operator-owned Custom Section Template.
 *
 * URI:   PATCH /api/v1/design/section-templates/custom/{sectionKey}
 * Scope: design.write
 */
final class MyronUpdateCustomSectionTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronCustomSectionTemplateActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/section-templates/custom/{sectionKey}',
            method:        'PATCH',
            domain:        'design',
            resource:      'section-template',
            verb:          'update-custom',
            inputSchema:   MyronCreateCustomSectionTemplateAction::inputSchema(['sectionKey']),
            outputSchema:  ['type' => 'object', 'properties' => ['sectionKey' => ['type' => 'string']]],
            requiredScope: MyronApiScopes::DESIGN_WRITE,
            summary:       'Update a Custom Section Template editable contract, defaults, and primitive bridge.',
            sideEffects:   ['updates custom_section_templates table'],
            preconditions: ['sectionKey references an existing custom section template'],
            postconditions:['custom section template read model is updated'],
            audienceClass: 4,
            adminAliases:  ['update-custom-section-template'],
            snapshotInclude: false,
            exposeToMcp:   true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('templates.custom_section');
        if ($entitlement !== null) {
            return $entitlement;
        }
        try {
            return MyronActionResult::ok($this->service->update((string) ($input['sectionKey'] ?? ''), $input, $caller));
        } catch (InvalidArgumentException $e) {
            return MyronActionResult::error('input_invalid', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }

    private function requireCapability(string $capability): ?MyronActionResult
    {
        if (!function_exists('myronEntitlementGate')) {
            return null;
        }
        try {
            $decision = myronEntitlementGate()->evaluate($capability);
        } catch (Throwable) {
            return MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
        }
        return in_array((string) ($decision['outcome'] ?? ''), ['allowed', 'warn'], true)
            ? null
            : MyronActionResult::error('entitlement_denied', 'This feature is not available for the current license.');
    }
}
