<?php

namespace MintyPHP\Tests\Architecture;

use MintyPHP\App\Module\ModuleManifestSchemaValidator;
use PHPUnit\Framework\TestCase;
use RuntimeException;

final class ModuleManifestSchemaValidationContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    public function testAllModuleManifestsValidateAgainstJsonSchema(): void
    {
        $root = $this->projectRootPath();
        $manifestFiles = glob($root . '/modules/*/module.php') ?: [];

        self::assertNotSame([], $manifestFiles, 'Expected at least one module manifest under modules/*/module.php');

        foreach ($manifestFiles as $manifestFile) {
            $rawManifest = require $manifestFile;
            self::assertIsArray($rawManifest, "Manifest {$manifestFile} must return array");

            $moduleId = basename(dirname($manifestFile));
            $relativeManifestPath = 'modules/' . $moduleId . '/module.php';

            ModuleManifestSchemaValidator::assertValid($rawManifest, $moduleId, $relativeManifestPath);
            self::addToAssertionCount(1);
        }
    }

    public function testSchemaValidatorRejectsUnknownRootProperty(): void
    {
        $manifest = [
            'id' => 'schema-fixture',
            'version' => '1.0.0',
            'enabled_by_default' => false,
            'load_order' => 100,
            'routes' => [],
            'public_paths' => [],
            'container_registrars' => [],
            'ui_slots' => [],
            'search_resources' => [],
            'asset_groups' => [],
            'layout_context_providers' => [],
            'session_providers' => [],
            'authorization_policies' => [],
            'permissions' => [],
            'scheduler_jobs' => [],
            'event_listeners' => [],
            'deactivation_handler' => null,
            'migrations_path' => null,
            'i18n_path' => null,
            'unexpected_root_property' => true,
        ];

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage("Manifest schema validation failed for module 'schema-fixture'");

        ModuleManifestSchemaValidator::assertValid(
            $manifest,
            'schema-fixture',
            'modules/schema-fixture/module.php'
        );
    }
}
