<?php

namespace App\Modules\ModuleManager\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Log;

class ModuleManagerServiceProvider extends ServiceProvider
{
    public function register()
    {
        foreach ($this->getModules() as $module) {
            if (!empty($module['enabled']) && $module['enabled'] && !empty($module['providers'])) {
                foreach ($module['providers'] as $provider) {
                    if (class_exists($provider)) {
                        try {
                            $this->app->register($provider);
                        } catch (\Throwable $e) {
                            Log::error("Failed to register module provider: {$provider}. Error: ".$e->getMessage());
                        }
                    }
                }
            }
        }
    }

    public function boot()
    {
        $routesPath = __DIR__ . '/../Routes/api.php';
        if (file_exists($routesPath)) {
            $this->loadRoutesFrom($routesPath);
        }
    }

    protected function getModules(): array
    {
        $modulesPath = base_path('app/Modules');
        $modules = [];

        if (!is_dir($modulesPath)) return $modules;

        foreach (scandir($modulesPath) as $folder) {
            // 🚫 Prevent infinite loop by skipping ModuleManager itself
            if (in_array($folder, ['.', '..', 'ModuleManager'])) continue;

            $moduleFolder = $modulesPath . DIRECTORY_SEPARATOR . $folder;
            if (!is_dir($moduleFolder)) continue;

            $moduleJsonPath = $moduleFolder . DIRECTORY_SEPARATOR . 'module.json';
            if (!file_exists($moduleJsonPath)) continue;

            try {
                $moduleData = json_decode(file_get_contents($moduleJsonPath), true, 512, JSON_THROW_ON_ERROR);
                if ($moduleData) $modules[$moduleData['slug']] = $moduleData;
            } catch (\Throwable $e) {
                Log::error("Error reading module.json in {$folder}: " . $e->getMessage());
            }
        }

        return $modules;
    }
}
