<?php

declare(strict_types=1);

/**
 * APO-194 Card 6 — Apply a stored design system definition.
 *
 * URI:   POST /api/v1/design/definitions/{definitionId}/apply-stored
 * Scope: administration.write  · exposeToMcp:TRUE (APO-205-006)
 */
final class MyronApplyStoredDefinitionAction implements MyronAction
{
    public function __construct(
        private readonly MyronDefinitionsActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/definitions/{definitionId}/apply-stored',
            method:        'POST',
            domain:        'design',
            resource:      'definition',
            verb:          'apply-stored',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['definitionId' => ['type' => 'string']],
                'required'   => ['definitionId'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['id' => ['type' => 'string'], 'name' => ['type' => 'string']]],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Apply a stored design definition (an operator-saved JSONM row) as the install\'s active definition; design tokens recompile to reflect the applied definition.',
            sideEffects:     ['updates active JSONM design definition; recompiles runtime design tokens'],
            preconditions:   ['definition exists in the stored list'],
            postconditions:  ['active definition reflects the applied id'],
            audienceClass:   2,
            adminAliases:    ['apply-stored'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->applyStored(
                (string) ($input['definitionId'] ?? ''),
                $caller
            ));
        } catch (MyronActionPreconditionError $e) {
            return MyronActionResult::error('precondition_failed', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
