<?php

declare(strict_types=1);

/** APO-194 Card 7 — GET /api/v1/design/templates/{templateId} */
final class MyronGetTemplateAction implements MyronAction
{
    public function __construct(
        private readonly MyronTemplateDefinitionRepository $repo,
        private readonly ?MyronContentRepository $content = null,
    ) {}

    public function metadata(): MyronActionMetadata
    {
        return new MyronActionMetadata(
            uri: '/api/v1/design/templates/{templateId}', method: 'GET',
            domain: 'design', resource: 'template', verb: 'get',
            inputSchema: ['type' => 'object', 'properties' => ['templateId' => ['type' => 'string']], 'required' => ['templateId']],
            outputSchema: ['type' => 'object', 'properties' => []],
            requiredScope: MyronApiScopes::DESIGN_READ,
            summary: 'Get a single page template definition or custom runtime template by ID.',
            audienceClass: 3,
            snapshotInclude: false,
            exposeToMcp: true,
        );
    }

    public function execute(array $input, MyronActionCallerContext $caller): MyronActionResult
    {
        $id = trim((string) ($input['templateId'] ?? ''));
        if ($id === '') return MyronActionResult::error('input_invalid', 'templateId is required.');
        $row = $this->repo->findTemplateById($id);
        if (!is_array($row) && $this->content !== null) {
            $runtime = $this->content->findRuntimeTemplateByIdOrSourceTemplateId($id);
            if (is_array($runtime)) {
                return MyronActionResult::ok($this->runtimeTemplatePayload($runtime));
            }
        }
        if (!is_array($row)) return MyronActionResult::error('precondition_failed', 'Template not found.');
        return MyronActionResult::ok($row);
    }

    /**
     * @param array<string, mixed> $runtime
     * @return array<string, mixed>
     */
    private function runtimeTemplatePayload(array $runtime): array
    {
        $schema = is_array($runtime['schema'] ?? null) ? $runtime['schema'] : [];
        return [
            'id' => (string) ($runtime['id'] ?? ''),
            'name' => (string) ($runtime['name'] ?? ''),
            'description' => (string) ($runtime['description'] ?? ''),
            'templateKey' => (string) ($runtime['template_key'] ?? ''),
            'sourceTemplateId' => (string) ($runtime['source_template_id'] ?? ''),
            'sourceBundleId' => (string) ($runtime['source_bundle_id'] ?? ''),
            'currentVersionId' => (string) ($runtime['current_version_id'] ?? ''),
            'versionNumber' => (int) ($runtime['version_number'] ?? 0),
            'viewName' => (string) ($runtime['view_name'] ?? ''),
            'schema' => $schema,
            'sections' => array_values(array_filter(
                is_array($schema['sections'] ?? null) ? $schema['sections'] : [],
                static fn (mixed $section): bool => is_array($section)
            )),
            'defaultContent' => is_array($schema['defaultContent'] ?? null) ? $schema['defaultContent'] : [],
            'templateLifecycle' => is_array($runtime['template_lifecycle'] ?? null) ? $runtime['template_lifecycle'] : [],
            'isCustomSiteTemplate' => (bool) ($runtime['is_custom_site_template'] ?? false),
            'isAvailablePageTemplate' => (bool) ($runtime['is_available_page_template'] ?? true),
        ];
    }
}
