<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions/{versionId}/duplicate',
            method:        'POST',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'duplicate',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['versionId' => ['type' => 'string']],
                'required'   => ['versionId'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => []],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Duplicate a navigation version — copy settings into a new row with a generated label.',
            sideEffects:     ['inserts new row in navigation_design_versions'],
            preconditions:   ['source version exists'],
            postconditions:  ['new version row exists, copy of source'],
            audienceClass:   4,
            adminAliases:    ['duplicate-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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