<?php

declare(strict_types=1);

/**
 * APO-194 Card 1 — Update a navigation version's settings.
 *
 * URI:   PATCH /api/v1/design/navigation/versions/{versionId}
 * Scope: design.write
 */
final class MyronUpdateNavigationVersionAction implements MyronAction
{
    public function __construct(
        private readonly MyronNavigationVersionActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions/{versionId}',
            method:        'PATCH',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'update',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'versionId' => ['type' => 'string'],
                    'settings'  => ['type' => 'object'],
                ],
                'required'   => ['versionId'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => []],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Update the settings payload (layout intent, density, link styling, etc.) for a saved navigation version.',
            sideEffects:     ['updates navigation_design_versions row'],
            preconditions:   ['version exists'],
            postconditions:  ['version settings reflect input payload'],
            audienceClass:   4,
            adminAliases:    ['update-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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