<?php

declare(strict_types=1);

/**
 * APO-194 Card 3 — Update document template metadata.
 *
 * URI:   PATCH /api/v1/design/document-templates/{templateId}
 * Scope: design.write
 */
final class MyronUpdateDocumentTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronDocumentTemplateActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/document-templates/{templateId}',
            method:        'PATCH',
            domain:        'design',
            resource:      'document-template',
            verb:          'update',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'templateId'  => ['type' => 'string'],
                    'name'        => ['type' => 'string'],
                    'description' => ['type' => 'string'],
                    'slug'        => ['type' => 'string'],
                ],
                'required'   => ['templateId'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['templateId' => ['type' => 'string']]],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Update document template metadata (name, description, slug).',
            sideEffects:     ['updates document_templates row'],
            preconditions:   ['template exists'],
            postconditions:  ['metadata reflects input'],
            audienceClass:   4,
            adminAliases:    ['update-document-template'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('templates.document');
        if ($entitlement !== null) {
            return $entitlement;
        }
        try {
            return MyronActionResult::ok($this->service->update(
                (string) ($input['templateId'] ?? ''),
                $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.');
    }
}
