<?php

declare(strict_types=1);

namespace Maestro\Core\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\ServiceProvider;
use Maestro\Core\Console\Commands\CoreInstallCommand;
use Maestro\Core\Http\Middleware\EnsureMaestroModuleEnabled;
use Maestro\Core\Modules\Customers\Providers\CustomersModuleServiceProvider;
use Maestro\Core\Modules\HourRegistration\Providers\HourRegistrationModuleServiceProvider;
use Maestro\Core\Modules\Invoices\Providers\InvoicesModuleServiceProvider;
use Maestro\Core\Modules\Items\Providers\ItemsModuleServiceProvider;
use Maestro\Core\Modules\Offers\Providers\OffersModuleServiceProvider;
use Maestro\Core\Services\AutoSyncPackageStubs;
use Maestro\Core\Support\AuthUserResolver;
use SocialiteProviders\Manager\SocialiteWasCalled;
use SocialiteProviders\Microsoft\MicrosoftExtendSocialite;

class CoreServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__.'/../../config/core.php', 'core');
        $this->mergeConfigFrom(__DIR__.'/../../config/datatable.php', 'datatable');
        $this->app->register(DataTablesServiceProvider::class);
    }

    public function boot(): void
    {
        $this->bindUserRouteParameter();
        $this->registerRouteMiddleware();

        Event::listen(
            SocialiteWasCalled::class,
            MicrosoftExtendSocialite::class.'@handle',
        );

        $this->loadModules();

        $this->loadMigrationsFrom(__DIR__.'/../../database/migrations');
        $this->loadRoutesFrom(__DIR__.'/../../routes/core.php');
        $this->loadViewsFrom(__DIR__.'/../../resources/views', 'maestro-core');
        $this->loadTranslationsFrom(__DIR__.'/../../lang', 'maestro');

        if ($this->app->runningInConsole()) {
            (new AutoSyncPackageStubs)->syncIfStubsAreNewer();
            $this->commands([CoreInstallCommand::class]);
        }

        $this->publishes([
            __DIR__.'/../../config/core.php' => config_path('core.php'),
            __DIR__.'/../../config/datatable.php' => config_path('datatable.php'),
        ], 'core-config');
    }

    private function loadModules(): void
    {
        // Published configs often list only some module keys; missing module keys mirror defaults in config/core.php.
        if (config('core.modules.customers', true) === true) {
            $this->app->register(CustomersModuleServiceProvider::class);
        }

        if (config('core.modules.hours', true) === true) {
            $this->app->register(HourRegistrationModuleServiceProvider::class);
        }

        if (config('core.modules.offers', true) === true) {
            $this->app->register(OffersModuleServiceProvider::class);
        }

        if (config('core.modules.invoices', true) === true) {
            $this->app->register(InvoicesModuleServiceProvider::class);
        }

        if (config('core.modules.items', true) === true) {
            $this->app->register(ItemsModuleServiceProvider::class);
        }
    }

    /**
     * Ensure `api/users/{user}` resolves the same User class as login (auth.providers.users.model),
     * so Spatie pivots stay on a consistent `model_type`.
     *
     * Apps may override with their own Route::bind('user', ...) registered after this provider.
     */
    private function bindUserRouteParameter(): void
    {
        Route::bind('user', function (string $value): Model {
            $class = AuthUserResolver::eloquentModelClass();

            /** @var Model $model */
            $model = $class::query()->whereKey($value)->firstOrFail();

            return $model;
        });
    }

    private function registerRouteMiddleware(): void
    {
        $router = $this->app->make(Router::class);
        $router->aliasMiddleware(
            'maestro.module',
            EnsureMaestroModuleEnabled::class,
        );
    }
}
