<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\File;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Register any application services.
     */
    public function register(): void
    {
        //
    }

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        $this->registerModuleRoutes();
        $this->registerModuleMigrations();
        $this->register(App\Providers\ResponseMacroServiceProvider::class);
        info('ResponseMacroServiceProvider booted.');
    }

    protected function registerModuleRoutes()
    {
        $modulesPath = app_path('Modules');

        if (File::exists($modulesPath)) {
            $modules = File::directories($modulesPath);

            foreach ($modules as $module) {
                $moduleName = basename($module);

                // API Routes
                if (File::exists("{$module}/routes/api.php")) {
                    Route::prefix('api')
                        ->middleware('api')
                        ->namespace("App\\Modules\\{$moduleName}\\Http\\Controllers")
                        ->group("{$module}/routes/api.php");
                }
            }
        }
    }

    protected function registerModuleMigrations()
    {
        $modulesPath = app_path('Modules');

        if (File::exists($modulesPath)) {
            $modules = File::directories($modulesPath);

            foreach ($modules as $module) {
                if (File::exists("{$module}/database/migrations")) {
                    $this->loadMigrationsFrom("{$module}/database/migrations");
                }
            }
        }
    }
}
