<?php

namespace Tests;

use Illuminate\Database\Connectors\ConnectionFactory;
use Illuminate\Database\Connectors\ConnectorInterface;
use Illuminate\Foundation\Application;
use Illuminate\Foundation\Bootstrap\LoadConfiguration;
use RuntimeException;

final class DatabaseSafety
{
    public static function protect(Application $app): void
    {
        if ($app->configurationIsCached()) {
            throw new RuntimeException('Tests refused: cached Laravel configuration may point to a shared database. Set APP_CONFIG_CACHE to a nonexistent test-only path; do not clear or rebuild the application cache.');
        }

        $app->afterBootstrapping(LoadConfiguration::class, function (Application $app): void {
            if (! $app->environment('testing')) {
                throw new RuntimeException('Tests refused: APP_ENV must be testing.');
            }

            $default = $app['config']->get('database.default');
            self::assertInMemory((array) $app['config']->get("database.connections.{$default}", []));
        });

        $app->extend('db.factory', fn (ConnectionFactory $factory, Application $app): ConnectionFactory => new class($app) extends ConnectionFactory
        {
            public function createConnector(array $config): ConnectorInterface
            {
                DatabaseSafety::assertInMemory($config);

                return parent::createConnector($config);
            }
        });
    }

    /** @param array<string, mixed> $config */
    public static function assertInMemory(array $config): void
    {
        if (($config['driver'] ?? null) !== 'sqlite'
            || ($config['database'] ?? null) !== ':memory:'
            || ! empty($config['url'])) {
            throw new RuntimeException('Tests refused: every database connection must use SQLite :memory: without a database URL. Persistent databases are forbidden.');
        }
    }
}
