<?php

declare(strict_types=1);

/**
 * APO-194 Card 1 — Activate a navigation version.
 *
 * URI:   POST /api/v1/design/navigation/versions/{versionId}/activate
 * Scope: design.write
 */
final class MyronActivateNavigationVersionAction implements MyronAction
{
    public function __construct(
        private readonly MyronNavigationVersionActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions/{versionId}/activate',
            method:        'POST',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'activate',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['versionId' => ['type' => 'string']],
                'required'   => ['versionId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'versionId'   => ['type' => 'string'],
                    'isActivated' => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Activate a navigation version — makes it eligible for selection as default or template binding.',
            sideEffects:     ['writes navigation_design_versions.is_activated'],
            preconditions:   ['version exists'],
            postconditions:  ['is_activated=1 for the version'],
            audienceClass:   4,
            adminAliases:    ['activate-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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