<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions',
            method:        'POST',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'create',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['name' => ['type' => 'string']],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['id' => ['type' => 'string'], 'name' => ['type' => 'string']]],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Create a new saved navigation version with an operator-chosen label.',
            sideEffects:     ['inserts row into navigation_design_versions'],
            preconditions:   [],
            postconditions:  ['version exists; activation defaults to false; not yet default'],
            audienceClass:   4,
            adminAliases:    ['create-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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