<?php

declare(strict_types=1);

/**
 * APO-194 Card 3 — Deactivate a document template.
 *
 * URI:   POST /api/v1/design/document-templates/{templateId}/deactivate
 * Scope: design.write
 */
final class MyronDeactivateDocumentTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronDocumentTemplateActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/document-templates/{templateId}/deactivate',
            method:        'POST',
            domain:        'design',
            resource:      'document-template',
            verb:          'deactivate',
            inputSchema:   [
                'type'       => 'object',
                'properties' => ['templateId' => ['type' => 'string']],
                'required'   => ['templateId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'templateId'  => ['type' => 'string'],
                    'deactivated' => ['type' => 'boolean'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Deactivate a document template; deactivated templates are excluded from operator pickers.',
            sideEffects:     ['writes document_templates.is_active=0'],
            preconditions:   ['template exists'],
            postconditions:  ['template marked deactivated'],
            audienceClass:   4,
            adminAliases:    ['deactivate-document-template'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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