<?php

declare(strict_types=1);

final class MyronSectionUsageService
{
    public function __construct(
        private readonly MyronSectionRegistryRepository $sections,
        private readonly MyronTemplateDefinitionRepository $templates,
    ) {
    }

    /**
     * @return array<string, list<array{templateId:string,bundleId:string,sourcePath:string,position:int,matchedBy:string}>>
     */
    public function usageIndex(): array
    {
        $index = [];
        foreach ($this->sections->listSectionKeys() as $sectionKey) {
            $index[$sectionKey] = [];
        }

        foreach ($this->templates->listTemplates() as $template) {
            $templateId = (string) ($template['id'] ?? '');
            $bundleId = (string) ($template['bundleId'] ?? '');
            $sourcePath = (string) ($template['_registry']['sourcePath'] ?? '');
            $bodySections = is_array($template['bodySections'] ?? null) ? $template['bodySections'] : [];

            foreach ($bodySections as $position => $section) {
                if (!is_array($section)) {
                    continue;
                }

                $explicitKey = trim((string) ($section['sectionKey'] ?? ''));
                $componentId = trim((string) ($section['componentId'] ?? ''));
                $matchedKey = '';
                $matchedBy = '';

                if ($explicitKey !== '' && array_key_exists($explicitKey, $index)) {
                    $matchedKey = $explicitKey;
                    $matchedBy = 'sectionKey';
                } elseif ($componentId !== '' && array_key_exists($componentId, $index)) {
                    $matchedKey = $componentId;
                    $matchedBy = 'legacyComponentId';
                }

                if ($matchedKey === '') {
                    continue;
                }

                $index[$matchedKey][] = [
                    'templateId' => $templateId,
                    'bundleId' => $bundleId,
                    'sourcePath' => $sourcePath,
                    'position' => (int) $position,
                    'matchedBy' => $matchedBy,
                ];
            }
        }

        return $index;
    }

    /**
     * @return list<array{templateId:string,bundleId:string,sourcePath:string,position:int,matchedBy:string}>
     */
    public function usageForSection(string $sectionKey): array
    {
        $index = $this->usageIndex();

        return $index[trim($sectionKey)] ?? [];
    }
}
