<?php

declare(strict_types=1);

/**
 * APO-194 Card 1 — Set the global default navigation version.
 *
 * URI:   PATCH /api/v1/design/navigation/versions/{versionId}/default
 * Scope: design.write
 */
final class MyronSetNavigationDefaultAction implements MyronAction
{
    public function __construct(
        private readonly MyronNavigationVersionActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions/{versionId}/default',
            method:        'PATCH',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'set-default',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['versionId' => ['type' => 'string']],
                'required'   => ['versionId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'versionId'        => ['type' => 'string'],
                    'previousDefault'  => ['type' => 'string'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Set the global default navigation version. Templates with chrome.navigation.inherit:"global" render the new default.',
            sideEffects:     ['writes navigation_design_versions.is_default'],
            preconditions:   ['version exists', 'version is activated'],
            postconditions:  ['exactly one navigation_design_versions row has is_default=1'],
            audienceClass:   4,
            adminAliases:    ['set-default-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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