<?php

declare(strict_types=1);

/**
 * APO-193 Card 5 — Clear a token override.
 *
 * URI:   DELETE /api/v1/design/tokens/patches/{tokenName}
 * Scope: design.write
 */
final class MyronClearTokenPatchAction implements MyronAction
{
    public function __construct(
        private readonly MyronTokenPatchActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/tokens/patches/{tokenName}',
            method:        'DELETE',
            domain:        'design',
            resource:      'token-patch',
            verb:          'clear',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['tokenName' => ['type' => 'string']],
                'required'   => ['tokenName'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'tokenName' => ['type' => 'string'],
                    'cleared'   => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Clear a single token override; the canonical token value resumes use.',
            sideEffects:     ['deletes from token_patches', 'recompiles runtime overrides'],
            preconditions:   [],
            postconditions:  ['no patch persists for tokenName'],
            audienceClass:   4,
            adminAliases:    ['clear-token-patch'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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