<?php

namespace Tests\Feature\BranchIsolation;

use RecursiveDirectoryIterator;
use RecursiveIteratorIterator;
use Tests\TestCase;

class Phase8LegacyResolverAuditTest extends TestCase
{
    public function test_no_legacy_pivot_only_branch_resolvers_remain_in_controllers(): void
    {
        $controllerRoot = app_path('Http/Controllers');
        $legacyFiles = [];

        foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($controllerRoot)) as $file) {
            if (! $file->isFile() || $file->getExtension() !== 'php') continue;

            $contents = file_get_contents($file->getPathname());
            if ($contents === false) continue;

            $usesPivotOnlyPluck = preg_match("/->branches\\(\\)->pluck\\(\\s*['\"]branches\\.id['\"]\\s*\\)/", $contents) === 1;
            $usesLegacySuperAdminTernary = preg_match("/hasRole\\(\\s*['\"]super-administrator['\"]\\s*\\).*?Branch::pluck\\(\\s*['\"]id['\"]\\s*\\)/s", $contents) === 1;

            if ($usesPivotOnlyPluck || $usesLegacySuperAdminTernary) {
                $legacyFiles[] = str_replace(base_path().DIRECTORY_SEPARATOR, '', $file->getPathname());
            }
        }

        sort($legacyFiles);

        $this->assertSame(
            [],
            $legacyFiles,
            'Unexpected legacy pivot-only branch resolver detected. Use BranchAccessService::accessibleBranchIds() instead.'
        );
    }
}
