<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/navigation/versions/{versionId}',
            method:        'DELETE',
            domain:        'design',
            resource:      'navigation-version',
            verb:          'delete',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['versionId' => ['type' => 'string']],
                'required'   => ['versionId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'versionId' => ['type' => 'string'],
                    'deleted'   => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Delete a navigation version. Cannot delete versions currently bound to a template — rebind those templates first.',
            sideEffects:     ['deletes row from navigation_design_versions'],
            preconditions:   ['version exists', 'version not referenced by any template chrome assignment'],
            postconditions:  ['version row removed'],
            audienceClass:   4,
            adminAliases:    ['delete-navigation-version'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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