<?php

declare(strict_types=1);

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

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

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