<?php

declare(strict_types=1);

/**
 * APO-193 Card 7 — Update a saved section variant.
 *
 * URI:   PATCH /api/v1/design/section-variants/{variantId}
 * Scope: design.write
 */
final class MyronUpdateSectionVariantAction implements MyronAction
{
    public function __construct(
        private readonly MyronSectionVariantActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/section-variants/{variantId}',
            method:        'PATCH',
            domain:        'design',
            resource:      'section-variant',
            verb:          'update',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'variantId'   => ['type' => 'string'],
                    'name'        => ['type' => 'string'],
                    'sectionKey'  => ['type' => 'string'],
                    'componentId' => ['type' => 'string'],
                    'variant'     => ['type' => 'string'],
                    'design'      => [
                        'type'       => 'object',
                        'properties' => [
                            'customCss'      => ['type' => 'string'],
                            'tokenOverrides' => ['type' => 'object'],
                            'editableTokens' => ['type' => 'array'],
                            'creative'       => [
                                'type'       => 'object',
                                'nullable'   => true,
                                'properties' => [
                                    'motionProfile'   => ['type' => 'string', 'nullable' => true],
                                    'sceneBackground' => ['type' => 'string', 'nullable' => true],
                                    'params'          => ['type' => 'object'],
                                ],
                            ],
                        ],
                    ],
                    'content'     => ['type' => 'object'],
                ],
                'required'   => ['variantId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id'   => ['type' => 'string'],
                    'name' => ['type' => 'string'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Update a saved section variant — rewrite design, content, component binding, or name.',
            sideEffects:     ['writes section_variants row'],
            preconditions:   ['variant exists'],
            postconditions:  ['variant row reflects input'],
            audienceClass:   4,
            adminAliases:    ['update-variant'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $entitlement = $this->requireCapability('templates.section_variants');
        if ($entitlement !== null) {
            return $entitlement;
        }
        try {
            $design = is_array($input['design'] ?? null) ? (array) $input['design'] : [];
            $content = is_array($input['content'] ?? null) ? (array) $input['content'] : [];
            return MyronActionResult::ok($this->service->update(
                (string) ($input['variantId'] ?? ''),
                (string) ($input['name'] ?? ''),
                (string) ($input['sectionKey'] ?? ''),
                (string) ($input['componentId'] ?? ''),
                (string) ($input['variant'] ?? 'default'),
                $design,
                $content,
                $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.');
    }
}
