<?php

declare(strict_types=1);

/**
 * APO-193 Card 5 — Clear orphan token overrides.
 *
 * URI:   POST /api/v1/design/tokens/patches/clear-orphans
 * Scope: design.write
 */
final class MyronClearOrphanTokenPatchesAction implements MyronAction
{
    public function __construct(
        private readonly MyronTokenPatchActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/tokens/patches/clear-orphans',
            method:        'POST',
            domain:        'design',
            resource:      'token-patch',
            verb:          'clear-orphans',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'cleared'   => ['type' => 'integer'],
                    'preserved' => ['type' => 'integer'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Clear orphan token overrides (patches whose tokens are no longer declared by any registry surface). Non-orphan patches are preserved.',
            sideEffects:     ['deletes from token_patches; recompiles runtime overrides'],
            preconditions:   ['token reference service is available'],
            postconditions:  ['orphans removed; non-orphans preserved'],
            audienceClass:   4,
            adminAliases:    ['clear-orphan-token-patches'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        try {
            return MyronActionResult::ok($this->service->clearOrphanPatches($caller));
        } catch (MyronActionPreconditionError $e) {
            return MyronActionResult::error('precondition_failed', $e->getMessage());
        } catch (Throwable $e) {
            return MyronActionResult::error('business_rule_failed', $e->getMessage());
        }
    }
}
