<?php

namespace Modules\Vrc\Providers;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Database\Eloquent\Factory;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Modules\Vrc\Console\SendRemindersCommand;

class VrcServiceProvider extends ServiceProvider
{
    /**
     * Boot the application events.
     */
    public function boot(Router $router): void
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('vrc.php'),
        ], 'config');

        $this->registerViews();
        $this->registerTranslations();
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->registerFactories();

        // VRC step-up two-factor auth gate (fail-open; only challenges opted-in users).
        $router->aliasMiddleware('vrc.2fa', \Modules\Vrc\Http\Middleware\VrcTwoFactor::class);

        if ($this->app->runningInConsole()) {
            $this->commands([SendRemindersCommand::class]);

            $this->app->booted(function () {
                /** @var Schedule $schedule */
                $schedule = $this->app->make(Schedule::class);
                $schedule->command('vrc:send-reminders')
                    ->dailyAt('08:00')
                    ->withoutOverlapping()
                    ->name('vrc-send-reminders');
            });
        }
    }

    /**
     * Register the service provider.
     *
     * Config is merged here (not in boot) so the contract bindings, which
     * read config('vrc.bindings'), are available during the register phase.
     */
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../Config/config.php', 'vrc');
        $this->app->register(RouteServiceProvider::class);
        $this->bindServiceContracts();
    }

    /**
     * Bind every VRC↔ERP service contract to its single configured
     * implementation (ERP adapter or VRC-native). See Config/config.php.
     */
    protected function bindServiceContracts(): void
    {
        $bindings = config('vrc.bindings', []);
        foreach ($bindings as $contract => $implementation) {
            $this->app->bind($contract, $implementation);
        }
    }

    public function registerViews(): void
    {
        $viewPath = resource_path('views/modules/vrc');
        $sourcePath = __DIR__ . '/../Resources/views';

        $this->publishes([$sourcePath => $viewPath], 'views');

        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/vrc';
        }, \Config::get('view.paths')), [$sourcePath]), 'vrc');
    }

    public function registerTranslations(): void
    {
        $langPath = resource_path('lang/modules/vrc');

        if (is_dir($langPath)) {
            $this->loadTranslationsFrom($langPath, 'vrc');
        } else {
            $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'vrc');
        }
    }

    public function registerFactories(): void
    {
        if (! app()->environment('production') && $this->app->runningInConsole()) {
            $factoryPath = __DIR__ . '/../Database/factories';
            if (is_dir($factoryPath)) {
                app(Factory::class)->load($factoryPath);
            }
        }
    }

    public function provides(): array
    {
        return [];
    }
}
