<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/definitions',
            method:        'POST',
            domain:        'design',
            resource:      'definition',
            verb:          'save-current',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'name'        => ['type' => 'string'],
                    'requestedId' => ['type' => 'string'],
                    'description' => ['type' => 'string'],
                ],
                'required'   => ['name'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['id' => ['type' => 'string'], 'name' => ['type' => 'string']]],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Save the current design state (tokens + layout settings) as a named JSONM design definition row in the stored set; does not change the install\'s active definition.',
            sideEffects:     ['inserts design_system_definitions row'],
            preconditions:   ['current JSONM design definition state is well-formed'],
            postconditions:  ['definition row exists with provided name'],
            audienceClass:   2,
            adminAliases:    ['save-current'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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