<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

class ListDataEndpointContractTest extends TestCase
{
    use ListContractFiles;
    use ProjectFileAssertionSupport;

    public function testDataEndpointsRequireGetGuard(): void
    {
        $files = $this->hardCutGridEndpointFiles();
        $this->assertCount(15, $files, 'Unexpected number of hard-cut grid data endpoints.');
        $this->assertNotContains('pages/admin/search/data().php', $files);

        foreach ($files as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringContainsString('gridRequireGetRequest();', $content, $file);
            $this->assertStringNotContainsString("strtoupper((string) (requestInput()->method())) !== 'GET'", $content, $file);
        }
    }

    public function testDataEndpointsDoNotInlineQueryAllIndexParsing(): void
    {
        foreach ($this->hardCutGridEndpointFiles() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringNotContainsString("requestInput()->queryAll()['", $content, $file);
            $this->assertStringContainsString('gridParseFiltersFromSchemaFile', $content, $file);
        }
    }

    public function testDataEndpointsDoNotUseLegacySingleIdAliases(): void
    {
        foreach ($this->hardCutGridEndpointFiles() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertSame(
                0,
                preg_match('/\?\?\s*\([^\n]*\[[\"\"][a-z_]+_id[\"\"]\]/', $content),
                $file
            );
        }
    }

    public function testAuditRepositoriesDoNotUseLegacySingleIdAliasFallbacks(): void
    {
        $files = [
            'modules/audit/lib/Module/Audit/Repository/ApiAuditLogRepository.php',
            'modules/audit/lib/Module/Audit/Repository/ImportAuditRunRepository.php',
            'modules/audit/lib/Module/Audit/Repository/UserLifecycleAuditRepository.php',
            'modules/audit/lib/Module/Audit/Repository/SystemAuditLogRepository.php',
        ];

        foreach ($files as $file) {
            $content = $this->readProjectFile($file);
            $this->assertSame(
                0,
                preg_match('/\[[\"\"][a-z_]+_ids[\"\"]\]\s*\?\?\s*\(\$filters\[[\"\"][a-z_]+_id[\"\"]\]/', $content),
                $file
            );
        }
    }

    public function testDataEndpointsUseDirectoryFilterSchema(): void
    {
        foreach ($this->hardCutGridEndpointSchemaFiles() as $file => $expectedHelperCall) {
            $content = $this->readProjectFile($file);
            $this->assertStringContainsString($expectedHelperCall, $content, $file);

            $schemaFile = str_contains($expectedHelperCall, '/runs-filter-schema.php')
                ? dirname($file) . '/runs-filter-schema.php'
                : dirname($file) . '/filter-schema.php';
            $schemaContent = $this->readProjectFile($schemaFile);
            $this->assertStringContainsString('gridFilterSchema', $schemaContent, $schemaFile);
        }
    }

    public function testDataEndpointsUseUnifiedGuardAbilityPatternExceptSearchResults(): void
    {
        foreach ($this->hardCutGridEndpointFiles() as $file) {
            $content = $this->readProjectFile($file);
            if ($file === 'pages/search/data().php') {
                $this->assertStringContainsString('Guard::requireLogin();', $content, $file);
                $this->assertStringNotContainsString('Guard::requireAbility', $content, $file);
                continue;
            }

            $this->assertMatchesRegularExpression(
                '/Guard::requireAbility(?:OrForbidden|DecisionOrForbidden)\(/',
                $content,
                $file
            );
            $this->assertStringNotContainsString('->authorize(', $content, $file);
        }
    }

    public function testDataEndpointsUseUnifiedDataAndTotalResponseHelper(): void
    {
        foreach ($this->hardCutGridEndpointFiles() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringContainsString('gridJsonDataResult(', $content, $file);
            $this->assertStringNotContainsString('Router::json($result);', $content, $file);
        }
    }
}
