<?php

namespace MintyPHP\Tests\Architecture;

use PHPUnit\Framework\TestCase;

class ListFilterContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    private function readTemplatePageModule(string $templateFile): string
    {
        $template = $this->readProjectFile($templateFile);
        $matched = preg_match("/assetVersion\\('js\\/pages\\/([^']+\\.js)'\\)/", $template, $captures);
        $this->assertSame(1, $matched, $templateFile . ' must reference a page module via assetVersion().');

        return $this->readProjectFile('web/js/pages/' . $captures[1]);
    }

    private function usesSharedListFiltersPartial(string $content): bool
    {
        return str_contains($content, "require templatePath('partials/app-list-filters.phtml');");
    }

    /**
     * @return list<string>
     */
    private function hardCutGridEndpointFiles(): array
    {
        return [
            'pages/address-book/data().php',
            'pages/search/data().php',
            'pages/admin/users/data().php',
            'pages/admin/tenants/data().php',
            'pages/admin/departments/data().php',
            'pages/admin/roles/data().php',
            'pages/admin/permissions/data().php',
            'pages/admin/mail-log/data().php',
            'pages/admin/scheduled-jobs/data().php',
            'pages/admin/scheduled-jobs/runs-data($id).php',
            'pages/admin/api-audit/data().php',
            'pages/admin/import-audit/data().php',
            'pages/admin/user-lifecycle-audit/data().php',
            'pages/admin/system-audit/data().php',
        ];
    }

    /**
     * @return array<string,string>
     */
    private function hardCutGridEndpointSchemaFiles(): array
    {
        return [
            'pages/address-book/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/search/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/users/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/tenants/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/departments/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/roles/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/permissions/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/mail-log/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/scheduled-jobs/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/scheduled-jobs/runs-data($id).php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/runs-filter-schema.php'",
            'pages/admin/api-audit/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/import-audit/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/user-lifecycle-audit/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
            'pages/admin/system-audit/data().php' => "gridParseFiltersFromSchemaFile(__DIR__ . '/filter-schema.php'",
        ];
    }

    /**
     * @return list<string>
     */
    private function listIndexTemplates(): array
    {
        return [
            'pages/address-book/index(default).phtml',
            'pages/search/index(default).phtml',
            'pages/admin/users/index(default).phtml',
            'pages/admin/tenants/index(default).phtml',
            'pages/admin/departments/index(default).phtml',
            'pages/admin/roles/index(default).phtml',
            'pages/admin/permissions/index(default).phtml',
            'pages/admin/mail-log/index(default).phtml',
            'pages/admin/scheduled-jobs/index(default).phtml',
            'pages/admin/api-audit/index(default).phtml',
            'pages/admin/import-audit/index(default).phtml',
            'pages/admin/user-lifecycle-audit/index(default).phtml',
            'pages/admin/system-audit/index(default).phtml',
        ];
    }

    /**
     * @return list<string>
     */
    private function listIndexActions(): array
    {
        return [
            'pages/address-book/index().php',
            'pages/search/index().php',
            'pages/admin/users/index().php',
            'pages/admin/tenants/index().php',
            'pages/admin/departments/index().php',
            'pages/admin/roles/index().php',
            'pages/admin/permissions/index().php',
            'pages/admin/mail-log/index().php',
            'pages/admin/scheduled-jobs/index().php',
            'pages/admin/api-audit/index().php',
            'pages/admin/import-audit/index().php',
            'pages/admin/user-lifecycle-audit/index().php',
            'pages/admin/system-audit/index().php',
        ];
    }

    /**
     * @return list<string>
     */
    private function drawerListTemplates(): array
    {
        return [
            'pages/address-book/index(default).phtml',
            'pages/admin/users/index(default).phtml',
            'pages/admin/tenants/index(default).phtml',
            'pages/admin/departments/index(default).phtml',
            'pages/admin/roles/index(default).phtml',
            'pages/admin/permissions/index(default).phtml',
            'pages/admin/mail-log/index(default).phtml',
            'pages/admin/scheduled-jobs/index(default).phtml',
            'pages/admin/api-audit/index(default).phtml',
            'pages/admin/import-audit/index(default).phtml',
            'pages/admin/user-lifecycle-audit/index(default).phtml',
            'pages/admin/system-audit/index(default).phtml',
        ];
    }

    /**
     * @return list<string>
     */
    private function searchOnlyTemplates(): array
    {
        return [
            'pages/search/index(default).phtml',
        ];
    }

    public function testDataEndpointsRequireGetGuard(): void
    {
        $files = $this->hardCutGridEndpointFiles();
        $this->assertCount(14, $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 = [
            'lib/Repository/Audit/ApiAuditLogRepository.php',
            'lib/Repository/Audit/ImportAuditRunRepository.php',
            'lib/Repository/Audit/UserLifecycleAuditRepository.php',
            'lib/Repository/Audit/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);
        }
    }

    public function testListTemplatesUseCentralToolbarRendererAndStandardListWrapper(): void
    {
        foreach ($this->listIndexTemplates() as $file) {
            $content = $this->readProjectFile($file);
            $moduleContent = $this->readTemplatePageModule($file);
            $usesPartial = $this->usesSharedListFiltersPartial($content);
            $this->assertTrue(
                $usesPartial || str_contains($content, 'renderGridFilterToolbar('),
                $file . ' does not render toolbar directly and does not include shared list-filters partial.'
            );
            $this->assertStringContainsString('initStandardListPage(', $moduleContent, $file);
            $this->assertStringNotContainsString('gridFiltersFromSchema(', $content, $file);
            $this->assertStringNotContainsString('data-toolbar-toggle', $content, $file);
            $this->assertStringNotContainsString('data-filter-overflow', $content, $file);
            $this->assertStringNotContainsString('data-filter-toggle', $content, $file);
            $this->assertSame(0, preg_match('/<select id=\"[^\"]*-filter\"/', $content), $file);
            $this->assertSame(0, preg_match('/<input[^>]*id=\"[^\"]*-filter\"/', $content), $file);
            $this->assertSame(0, preg_match('/filters:\s*\[/', $content), $file);
        }
    }

    public function testListActionsExposeSplitToolbarSchemasAndChipMeta(): void
    {
        foreach ($this->listIndexActions() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringContainsString('$searchToolbarFilterSchema', $content, $file);
            $this->assertStringContainsString('$drawerToolbarFilterSchema', $content, $file);
            $this->assertStringContainsString('$filterChipMeta', $content, $file);
        }
    }

    public function testDrawerListTemplatesUseDrawerAndActiveFilterChips(): void
    {
        foreach ($this->drawerListTemplates() as $file) {
            $content = $this->readProjectFile($file);
            $moduleContent = $this->readTemplatePageModule($file);
            $usesPartial = $this->usesSharedListFiltersPartial($content);
            $this->assertStringContainsString("mode: 'drawer'", $moduleContent, $file);
            if (!$usesPartial) {
                $this->assertStringContainsString('data-filter-drawer-open', $content, $file);
                $this->assertStringContainsString('data-filter-drawer-apply', $content, $file);
                $this->assertStringContainsString('data-active-filter-chips', $content, $file);
            }
            $this->assertStringNotContainsString('data-filter-drawer-reset', $content, $file);
        }
    }

    public function testSearchOnlyTemplatesDoNotUseDrawerControls(): void
    {
        foreach ($this->searchOnlyTemplates() as $file) {
            $content = $this->readProjectFile($file);
            $moduleContent = $this->readTemplatePageModule($file);
            $this->assertStringContainsString("mode: 'search-only'", $moduleContent, $file);
            $this->assertStringNotContainsString('data-filter-drawer-open', $content, $file);
            $this->assertStringNotContainsString('data-filter-drawer-apply', $content, $file);
            $this->assertStringNotContainsString('data-active-filter-chips', $content, $file);
        }
    }
}
