<?php

declare(strict_types=1);

it('keeps schema bootstrap SQL compatible with the MySQL runner', function (): void {
    $roots = [
        app_path('classes'),
        app_path('modules'),
        app_path('objects'),
        app_path('routes'),
        app_path('traits'),
        app_path('tests/Support'),
    ];

    $unsupportedPattern = '/\bALTER\s+TABLE\b[^;]*(?:ADD|DROP)\s+COLUMN\s+IF\s+(?:NOT\s+)?EXISTS\b|\b(?:CREATE|ADD)\s+(?:UNIQUE\s+)?INDEX\s+IF\s+NOT\s+EXISTS\b/is';
    $violations = [];

    foreach ($roots as $root) {
        if (!is_dir($root)) {
            continue;
        }

        $iterator = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($root, FilesystemIterator::SKIP_DOTS)
        );

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

            $path = str_replace('\\', '/', $file->getPathname());
            if (str_contains($path, '/vendor/')) {
                continue;
            }

            $contents = file_get_contents($file->getPathname());
            if ($contents !== false && preg_match($unsupportedPattern, $contents) === 1) {
                $violations[] = str_replace('\\', '/', substr($file->getPathname(), strlen(app_path()) + 1));
            }
        }
    }

    sort($violations);

    expect($violations)->toBe(
        [],
        'Avoid MariaDB-only schema syntax in CI-runner MySQL bootstraps: ' . implode(', ', $violations)
    );
});
