<?php

namespace MintyPHP\Tests\Architecture;

use FilesystemIterator;
use PHPUnit\Framework\TestCase;
use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;

final class CoreTemplateIsolationTest extends TestCase
{
    public function testCoreTemplatesDoNotReferenceModuleSpecificLayoutNavKeys(): void
    {
        $projectRoot = dirname(__DIR__, 2);
        $templatesDir = $projectRoot . '/templates';
        $modulesDir = $projectRoot . '/modules';

        if (!is_dir($templatesDir) || !is_dir($modulesDir)) {
            self::markTestSkipped('templates/ or modules/ directory missing.');
        }

        $moduleIds = [];
        foreach (scandir($modulesDir) ?: [] as $entry) {
            if ($entry === '.' || $entry === '..') {
                continue;
            }
            if (!is_dir($modulesDir . '/' . $entry)) {
                continue;
            }
            $moduleIds[] = $entry;
        }

        $violations = [];
        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($templatesDir, FilesystemIterator::SKIP_DOTS),
            RecursiveIteratorIterator::LEAVES_ONLY
        );

        foreach ($iterator as $file) {
            if ($file->getExtension() !== 'phtml') {
                continue;
            }
            $path = $file->getPathname();
            $content = file_get_contents($path);
            if (!is_string($content)) {
                continue;
            }

            foreach ($moduleIds as $moduleId) {
                if (preg_match("/layoutNav\[['\"]" . preg_quote($moduleId, '/') . "(\\.|['\"])" . "/", $content) === 1) {
                    $violations[] = str_replace($projectRoot . '/', '', $path) . ' references layoutNav module key for ' . $moduleId;
                }
            }
        }

        self::assertSame([], $violations, "Core templates reference module layout keys:\n" . implode("\n", $violations));
    }
}
