<?php

namespace Tests\Traits;

use Illuminate\Contracts\Console\Kernel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Foundation\Testing\RefreshDatabaseState;

trait RefreshDatabaseWithProject
{
    use RefreshDatabase;

    /**
     * Refresh the test database once, then use transactions for each test.
     */
    protected function refreshTestDatabase(): void
    {
        if (! RefreshDatabaseState::$migrated) {
            $this->runAllMigrations();
            RefreshDatabaseState::$migrated = true;
        }

        $this->beginDatabaseTransaction();
    }

    /**
     * Run all migrations (base + project) once.
     */
    protected function runAllMigrations(): void
    {
        $this->artisan('migrate:fresh', [
            '--drop-views' => true,
            '--force' => true,
        ]);

        $this->artisan('migrate', [
            '--path' => '/database/migrations/project',
            '--force' => true,
        ]);

        $this->app[Kernel::class]->setArtisan(null);
    }
}
