<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Support\Facades\Artisan;
use Illuminate\Support\Facades\File;

abstract class TestCase extends BaseTestCase
{
    use CreatesApplication;

    protected string $testingDatabasePath;

    protected static bool $databaseMigrated = false;

    protected function setUp(): void
    {
        parent::setUp();

        if (app()->environment('production')) {
            $this->fail('Refusing to run tests against the production environment.');
        }

        $this->testingDatabasePath = storage_path('framework/testing/test-database.sqlite');

        File::ensureDirectoryExists(dirname($this->testingDatabasePath));

        if (! file_exists($this->testingDatabasePath)) {
            touch($this->testingDatabasePath);
        }

        config([
            'database.default' => 'sqlite',
            'database.connections.sqlite.database' => $this->testingDatabasePath,
        ]);

        if (! static::$databaseMigrated) {
            Artisan::call('migrate', [
                '--database' => 'sqlite',
                '--force' => true,
            ]);

            static::$databaseMigrated = true;
        }
    }

    public static function tearDownAfterClass(): void
    {
        parent::tearDownAfterClass();

        $testingDatabasePath = storage_path('framework/testing/test-database.sqlite');

        if (file_exists($testingDatabasePath)) {
            unlink($testingDatabasePath);
        }

        static::$databaseMigrated = false;
    }
}
