<?php

declare(strict_types=1);

/**
 * APO-194 Card 6 — Remove a stored design system definition.
 *
 * URI:   DELETE /api/v1/design/definitions/{definitionId}/stored
 * Scope: administration.write  · exposeToMcp:TRUE (APO-205-006)
 */
final class MyronRemoveStoredDefinitionAction implements MyronAction
{
    public function __construct(
        private readonly MyronDefinitionsActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/definitions/{definitionId}/stored',
            method:        'DELETE',
            domain:        'design',
            resource:      'definition',
            verb:          'remove-stored',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['definitionId' => ['type' => 'string']],
                'required'   => ['definitionId'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => []],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Remove a stored design definition (an operator-saved JSONM row); if it was the install\'s active definition, the install falls back to the baseline JSONM definition.',
            sideEffects:     ['deletes JSONM design definition row; may reset active to baseline'],
            preconditions:   ['definition exists'],
            postconditions:  ['definition removed'],
            audienceClass:   2,
            adminAliases:    ['remove-stored'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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