<?php

namespace MintyPHP\Tests\Architecture;

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

/**
 * GR-SEC-006: User-uploaded files MUST go to storage/, never web/.
 * Exception: Favicon services write derived images to web/favicon/ because
 * favicons must be publicly accessible by browsers.
 */
class FileStorageContractTest extends TestCase
{
    use ProjectFileAssertionSupport;

    /** Services that legitimately write to web/ for favicon delivery. */
    private const WEB_WRITE_EXEMPT_FILES = [
        'lib/Service/Branding/BrandingFaviconService.php',
        'lib/Service/Tenant/TenantFaviconService.php',
    ];

    public function testNoServiceWritesFilesToWebDirectory(): void
    {
        $root = $this->projectRootPath();
        $serviceDir = $root . '/lib/Service';
        $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($serviceDir));

        $violations = [];

        /** @var \SplFileInfo $file */
        foreach ($iterator as $file) {
            if (!$file->isFile() || $file->getExtension() !== 'php') {
                continue;
            }

            $relativePath = str_replace($root . '/', '', $file->getPathname());

            if (in_array($relativePath, self::WEB_WRITE_EXEMPT_FILES, true)) {
                continue;
            }

            $content = (string) file_get_contents($file->getPathname());

            $hasFileWrite = preg_match('/\bmove_uploaded_file\s*\(/', $content)
                || preg_match('/\bfile_put_contents\s*\(/', $content);

            if (!$hasFileWrite) {
                continue;
            }

            $hasWebPath = preg_match('/[\'"]web\//', $content)
                || preg_match('/\/web\/[a-z]/', $content);

            if ($hasWebPath) {
                $violations[] = $relativePath;
            }
        }

        sort($violations);

        $this->assertSame(
            [],
            $violations,
            "Service files writing to web/ directory (GR-SEC-006):\n" . implode("\n", $violations)
        );
    }

    public function testNoPagesWriteFilesToFilesystem(): void
    {
        $violations = array_merge(
            $this->findPatternMatchesInPhpFiles('pages', '/\bmove_uploaded_file\s*\(/'),
            $this->findPatternMatchesInPhpFiles('pages', '/\bfile_put_contents\s*\(/')
        );
        $violations = array_values(array_unique($violations));
        sort($violations);

        $this->assertSame(
            [],
            $violations,
            "Pages must not write files directly — delegate to Service layer (GR-SEC-006):\n" . implode("\n", $violations)
        );
    }
}
