<?php

namespace MintyPHP\Tests\Architecture;

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

class AdminActionRequestGuardContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    public function testAdminActionsDoNotInlineLegacyMethodChecks(): void
    {
        foreach ($this->adminActionFiles() 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 testAdminActionsDoNotInlineLegacyCsrfChecks(): void
    {
        foreach ($this->adminActionFiles() as $file) {
            $content = $this->readProjectFile($file);
            $this->assertStringNotContainsString('Session::checkCsrfToken()', $content, $file);
        }
    }

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

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

            $relativePath = 'pages/admin/' . ltrim(str_replace($adminRoot, '', $file->getPathname()), '/');
            $files[] = $relativePath;
        }

        sort($files);
        $this->assertNotEmpty($files, 'Expected admin action files in pages/admin.');
        return $files;
    }
}
