<?php

declare(strict_types=1);

/**
 * APO-224 — Create a net-new operator-owned Custom Site Template.
 *
 * URI:   POST /api/v1/design/site-templates/custom
 * Scope: design.write
 */
final class MyronCreateCustomSiteTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronTemplateDuplicationActionService $service,
    ) {
    }

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri:           '/api/v1/design/site-templates/custom',
            method:        'POST',
            domain:        'design',
            resource:      'site-template',
            verb:          'create-custom',
            inputSchema:   [
                'type'       => 'object',
                'properties' => [
                    'name' => ['type' => 'string'],
                    'description' => ['type' => 'string'],
                    'siteTypeCode' => ['type' => 'string'],
                ],
                'required'   => ['name'],
            ],
            outputSchema:  [
                'type'       => 'object',
                'properties' => [
                    'id' => ['type' => 'string'],
                    'source_template_id' => ['type' => 'string'],
                    'lifecycle' => ['type' => 'object'],
                ],
            ],
            requiredScope:   MyronApiScopes::DESIGN_WRITE,
            summary:         'Create a blank Custom Site Template for governed architectural section composition.',
            sideEffects:     ['inserts page_templates row', 'inserts page_template_versions row'],
            preconditions:   ['caller can manage design'],
            postconditions:  ['custom Site Template exists; not yet available as a Page Template'],
            audienceClass:   4,
            adminAliases:    ['create-custom-site-template'],
            snapshotInclude: false,
            exposeToMcp:     true,
        );
    }

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