<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions/{versionId}/deactivate',
            method:        'POST',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'deactivate',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['versionId' => ['type' => 'string']],
                'required'   => ['versionId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'versionId'   => ['type' => 'string'],
                    'isActivated' => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Deactivate a navigation version. Cannot deactivate the current global default — set a different default first.',
            sideEffects:     ['writes navigation_design_versions.is_activated'],
            preconditions:   ['version exists', 'version is not the current global default'],
            postconditions:  ['is_activated=0 for the version'],
            audienceClass:   4,
            adminAliases:    ['deactivate-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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