<?php

namespace MintyPHP\Tests\Architecture;

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

class CorePageRequestGuardContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    public function testCorePagesDoNotInlineLegacyMethodChecks(): void
    {
        foreach ($this->corePageFiles() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringNotContainsString('requestInput()->method()', $content, $file);
            $this->assertStringNotContainsString('(requestInput()->method())', $content, $file);
            $this->assertStringNotContainsString("strtoupper((string) (requestInput()->method()))", $content, $file);
        }
    }

    public function testCorePagesDoNotInlineLegacyCsrfChecks(): void
    {
        foreach ($this->corePageFiles() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringNotContainsString('Session::checkCsrfToken()', $content, $file);
        }
    }

    /**
     * @return array<int, string>
     */
    private function corePageFiles(): array
    {
        $pagesRoot = $this->projectRootPath() . '/pages';
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($pagesRoot));
        $files = [];

        foreach ($iterator as $file) {
            if (!$file->isFile() || $file->getExtension() !== 'php') {
                continue;
            }

            $relativePath = 'pages/' . ltrim(str_replace($pagesRoot, '', $file->getPathname()), '/');
            if (str_starts_with($relativePath, 'pages/admin/')) {
                continue;
            }
            $files[] = $relativePath;
        }

        sort($files);
        $this->assertNotEmpty($files, 'Expected non-admin core pages.');
        return $files;
    }
}
