<?php

declare(strict_types=1);

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

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/tokens/patches',
            method:        'POST',
            domain:        'design',
            resource:      'token-patch',
            verb:          'save',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'tokenName'  => ['type' => 'string'],
                    'patchValue' => ['type' => 'string'],
                    'patchNote'  => ['type' => 'string'],
                ],
                'required'   => ['tokenName', 'patchValue'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'tokenName'  => ['type' => 'string'],
                    'patchValue' => ['type' => 'string'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Save a token override (patch). Overrides the canonical token value for the install; persists across sessions; recompiles runtime patches.',
            sideEffects:     ['writes token_patches table', 'recompiles runtime overrides CSS'],
            preconditions:   ['tokenName references a declared token'],
            postconditions:  ['patch persists; runtime overrides reflect new value'],
            audienceClass:   4,
            adminAliases:    ['save-token-patch'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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