<?php

namespace Tests\Traits;

use Illuminate\Support\Facades\Artisan;

/**
 * Trait to handle module migrations in tests.
 *
 * Module migrations are not automatically included when RefreshDatabase
 * runs migrate:fresh. This trait adds support for running module migrations
 * after the database refresh.
 *
 * Usage: In your test class, define:
 *   protected array $modulesToMigrate = ['AIAgentFramework'];
 */
trait UsesModuleMigrations
{
    /**
     * Run module migrations after the RefreshDatabase trait has reset the database.
     * This method is automatically called by Laravel's RefreshDatabase trait.
     */
    protected function afterRefreshingDatabase(): void
    {
        $this->runModuleMigrations();
    }

    /**
     * Run migrations for specified modules.
     */
    protected function runModuleMigrations(): void
    {
        $modules = property_exists($this, 'modulesToMigrate') ? $this->modulesToMigrate : [];

        foreach ($modules as $module) {
            $migrationPath = base_path("Modules/{$module}/Database/migrations");

            if (is_dir($migrationPath)) {
                Artisan::call('migrate', [
                    '--path' => "Modules/{$module}/Database/migrations",
                    '--no-interaction' => true,
                ]);
            }
        }
    }
}
