<?php

declare(strict_types=1);

namespace Maestro\Core\Support;

use Illuminate\Support\Facades\Schema;
use Maestro\Core\Models\MaestroModule;
use Throwable;

final class ModuleRuntimeState
{
    public static function shouldLoadMigrations(string $slug, bool $configDefault = true): bool
    {
        if (! self::isConfigured($slug, $configDefault)) {
            return false;
        }

        // Package tests use RefreshDatabase and do not bootstrap runtime toggles first.
        if (app()->runningUnitTests()) {
            return true;
        }

        return self::isRuntimeEnabled($slug);
    }

    public static function shouldRunSeeder(string $slug, bool $configDefault = true): bool
    {
        return self::shouldLoadMigrations($slug, $configDefault);
    }

    public static function isRuntimeEnabled(string $slug): bool
    {
        if (! self::hasModuleRegistryTable()) {
            return false;
        }

        return MaestroModule::query()
            ->where('slug', $slug)
            ->where('is_enabled', true)
            ->exists();
    }

    private static function isConfigured(string $slug, bool $configDefault): bool
    {
        return config("core.modules.{$slug}", $configDefault) === true;
    }

    private static function hasModuleRegistryTable(): bool
    {
        try {
            return Schema::hasTable('maestro_modules');
        } catch (Throwable) {
            return false;
        }
    }
}
