<?php

declare(strict_types=1);

/**
 * APO-194 Card 6 — Apply a selectable design system definition.
 *
 * URI:   POST /api/v1/design/definitions/{definitionId}/apply
 * Scope: administration.write  · exposeToMcp:TRUE (APO-205-006)
 *
 * APO-205-006: flipped to exposeToMcp:true. Substrate test — an MCP agent with
 * administration.write parity with the operator must be able to apply a theme,
 * which is the operator's most common authoring action on this surface.
 */
final class MyronApplyDefinitionAction implements MyronAction
{
    public function __construct(
        private readonly MyronDefinitionsActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/definitions/{definitionId}/apply',
            method:        'POST',
            domain:        'design',
            resource:      'definition',
            verb:          'apply',
            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 selectable JSONM design definition — either a packaged archetype or an imported file. Replaces the install\'s active design definition; recompiles design tokens.',
            sideEffects:     ['updates active JSONM design definition; recompiles runtime design tokens'],
            preconditions:   ['definition is selectable'],
            postconditions:  ['active definition reflects the applied id'],
            audienceClass:   2,
            adminAliases:    ['apply-definition'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->applyDefinition(
                (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());
        }
    }
}
