<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\Relation;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;

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

    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Model::shouldBeStrict(! app()->isProduction());

        Relation::morphMap(config('ecommerce.models'));

        $this->loadMigrationsFrom($this->findModuleMigrations());
        // $this->listenDB();
    }

    /**
     * Find Module migrations
     *
     * @return array<int, string>
     */
    public function findModuleMigrations(): array
    {
        /** @var array<int, string> */
        $modulesDir = scandir(modules_path());

        $migrationDirectories = [];
        foreach ($modulesDir as $module) {
            if (is_dir(modules_path($module.'/Database/Migrations'))) {
                $migrationDirectories[] = modules_path($module.'/Database/Migrations');
            }
        }

        return $migrationDirectories;
    }

    public function listenDB(): void
    {
        if (! app()->isLocal()) {
            return;
        }

        DB::listen(function ($query) {
            Log::info($query->sql, $query->bindings, $query->time);
        });
    }
}
