<?php

declare(strict_types=1);

/**
 * APO-194 Card 3 — Create a document template from an uploaded file.
 *
 * URI:   POST /api/v1/design/document-templates
 * Scope: design.write
 *
 * Caller must supply `fileId` — a file row already created via the Files
 * upload action (Card 4). Future enhancement: accept a JSON-content envelope
 * inline for one-call upload+bind; deferred for the substrate-clean shape.
 */
final class MyronCreateDocumentTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronDocumentTemplateActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/document-templates',
            method:        'POST',
            domain:        'design',
            resource:      'document-template',
            verb:          'create',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'fileId'      => ['type' => 'string'],
                    'name'        => ['type' => 'string'],
                    'description' => ['type' => 'string'],
                    'slug'        => ['type' => 'string'],
                ],
                'required'   => ['fileId', 'name'],
            ],
            outputSchema:  ['type' => 'object', 'properties' => ['id' => ['type' => 'string']]],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Create a document template from an existing file row. The fileId is produced by the Files upload action.',
            sideEffects:     ['inserts document_templates row'],
            preconditions:   ['file exists in files table', 'file is a document MIME type'],
            postconditions:  ['document template row exists; bound to file'],
            audienceClass:   4,
            adminAliases:    ['upload-document-template'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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