<?php

namespace Tests\Unit;

use Illuminate\Config\Repository;
use Illuminate\Database\DatabaseServiceProvider;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use PHPUnit\Framework\Attributes\DataProvider;
use PHPUnit\Framework\TestCase;
use RuntimeException;
use Symfony\Component\Process\Process;
use Tests\DatabaseSafety;

class TestDatabaseSafetyTest extends TestCase
{
    /** @return array<string, array{array<string, mixed>}> */
    public static function unsafeConnections(): array
    {
        return [
            'mysql' => [['driver' => 'mysql', 'database' => ':memory:']],
            'persistent sqlite' => [['driver' => 'sqlite', 'database' => '/never-open-this.sqlite']],
            'database URL override' => [['driver' => 'sqlite', 'database' => ':memory:', 'url' => 'mysql://invalid/never-connect']],
            'missing database' => [['driver' => 'sqlite']],
        ];
    }

    #[DataProvider('unsafeConnections')]
    public function test_persistent_connections_are_rejected_before_connection_creation(array $connection): void
    {
        $app = new Application(dirname(__DIR__, 2));
        DatabaseSafety::protect($app);
        $app->register(DatabaseServiceProvider::class);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Persistent databases are forbidden');

        $app->make('db.factory')->createConnector($connection);
    }

    public function test_in_memory_connections_remain_usable(): void
    {
        $app = new Application(dirname(__DIR__, 2));
        DatabaseSafety::protect($app);
        $app->register(DatabaseServiceProvider::class);

        $connection = $app->make('db.factory')->make([
            'driver' => 'sqlite', 'database' => ':memory:', 'prefix' => '',
        ]);

        $this->assertSame(1, $connection->selectOne('SELECT 1 AS safe')->safe);
    }

    public function test_a_secondary_connection_cannot_be_switched_to_a_persistent_database(): void
    {
        $app = new Application(dirname(__DIR__, 2));
        DatabaseSafety::protect($app);
        $app->instance('config', new Repository(['database' => ['connections' => [
            'secondary' => ['driver' => 'sqlite', 'database' => '/never-open-this.sqlite'],
        ]]]));
        $app->register(DatabaseServiceProvider::class);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Persistent databases are forbidden');

        $app->make('db')->connection('secondary')->getPdo();
    }

    public function test_unsafe_effective_configuration_is_rejected_before_providers_boot(): void
    {
        $app = new Application(dirname(__DIR__, 2));
        $app->afterBootstrapping(LoadConfiguration::class, function (Application $app): void {
            $app['config']->set('database.default', 'unsafe');
            $app['config']->set('database.connections.unsafe', [
                'driver' => 'mysql', 'database' => 'never-connect',
            ]);
        });
        DatabaseSafety::protect($app);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('Persistent databases are forbidden');

        $app->bootstrapWith([LoadConfiguration::class]);
    }

    public function test_non_testing_environment_is_rejected_before_providers_boot(): void
    {
        $app = new Application(dirname(__DIR__, 2));
        $app->afterBootstrapping(LoadConfiguration::class, function (Application $app): void {
            $app->detectEnvironment(fn (): string => 'production');
        });
        DatabaseSafety::protect($app);

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('APP_ENV must be testing');

        $app->bootstrapWith([LoadConfiguration::class]);
    }

    public function test_cached_configuration_is_rejected_without_loading_it(): void
    {
        $app = new class(dirname(__DIR__, 2)) extends Application
        {
            public function configurationIsCached(): bool
            {
                return true;
            }
        };

        $this->expectException(RuntimeException::class);
        $this->expectExceptionMessage('cached Laravel configuration');

        DatabaseSafety::protect($app);
    }

    public function test_the_actual_test_case_blocks_cached_configuration_before_application_boot(): void
    {
        $cache = tempnam(sys_get_temp_dir(), 'test-database-guard-');
        $this->assertNotFalse($cache);

        try {
            file_put_contents($cache, '<?php throw new RuntimeException("Unsafe cache was loaded");');

            $process = new Process([
                PHP_BINARY, '-r',
                'require "vendor/autoload.php"; (new class("probe") extends \Tests\TestCase {})->createApplication();',
            ], dirname(__DIR__, 2), ['APP_CONFIG_CACHE' => $cache]);
            $process->run();

            $this->assertFalse($process->isSuccessful());
            $output = $process->getOutput().$process->getErrorOutput();
            $this->assertStringContainsString('Tests refused: cached Laravel configuration', $output);
            $this->assertStringNotContainsString('Unsafe cache was loaded', $output);
        } finally {
            unlink($cache);
        }
    }

    public function test_the_actual_test_case_blocks_inherited_persistent_database_settings(): void
    {
        $process = new Process([
            PHP_BINARY, '-r',
            'require "vendor/autoload.php"; (new class("probe") extends \Tests\TestCase {})->createApplication();',
        ], dirname(__DIR__, 2), [
            'APP_ENV' => 'testing',
            'APP_CONFIG_CACHE' => 'bootstrap/cache/testing-config.php',
            'DB_CONNECTION' => 'mysql',
            'DB_DATABASE' => 'never-connect',
            'DB_URL' => '',
        ]);
        $process->run();

        $this->assertFalse($process->isSuccessful());
        $this->assertStringContainsString(
            'Tests refused: every database connection must use SQLite :memory:',
            $process->getOutput().$process->getErrorOutput(),
        );
    }
}
