<?php

declare(strict_types=1);

/**
 * APO-224 — Make a Custom Site Template available as a Page Template.
 *
 * URI:   POST /api/v1/design/site-templates/custom/{templateId}/register-page-template
 * Scope: design.write
 */
final class MyronRegisterCustomSiteTemplateAsPageTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronTemplateDuplicationActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/site-templates/custom/{templateId}/register-page-template',
            method:        'POST',
            domain:        'design',
            resource:      'site-template',
            verb:          'register-page-template',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'templateId' => ['type' => 'string'],
                ],
                'required'   => ['templateId'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id' => ['type' => 'string'],
                    'source_template_id' => ['type' => 'string'],
                    'lifecycle' => ['type' => 'object'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Register an operator-owned Custom Site Template as available for Page Template design and Content page creation.',
            sideEffects:     ['updates page_template_versions.schema_json lifecycle metadata'],
            preconditions:   ['templateId resolves to a Custom Site Template'],
            postconditions:  ['Custom Site Template is discoverable as an available Page Template'],
            audienceClass:   4,
            adminAliases:    ['make-custom-template-available'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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