<?php

namespace Modules\PortalApi\Providers;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Contracts\Foundation\CachesConfiguration;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Modules\PortalApi\Console\BuildPwaCommand;
use Modules\PortalApi\Console\GenerateVapidKeysCommand;
use Modules\PortalApi\Console\PushAppointmentRemindersCommand;
use Modules\PortalApi\Console\PushVaxRemindersCommand;
use Modules\PortalApi\Console\TestPushCommand;
use Modules\PortalApi\Http\Middleware\PortalAuth;
use Modules\PortalApi\Services\Sms\LogSmsGateway;
use Modules\PortalApi\Services\Sms\PortalSmsGateway;

class PortalApiServiceProvider extends ServiceProvider
{
    public function boot(Router $router)
    {
        $this->loadViewsFrom(__DIR__ . '/../Resources/views', 'portalApi');
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->mergeConfigFrom(__DIR__ . '/../Config/portal_push.php', 'portal_push');

        $router->aliasMiddleware('portal-api.auth', PortalAuth::class);
        $router->aliasMiddleware('portal-api.demo-auth', PortalAuth::class);

        if ($this->app->runningInConsole()) {
            $this->commands([
                BuildPwaCommand::class,
                GenerateVapidKeysCommand::class,
                TestPushCommand::class,
                PushVaxRemindersCommand::class,
                PushAppointmentRemindersCommand::class,
            ]);

            // Schedule the reminder commands without touching the app's
            // Console/Kernel. Daily 08:00 for vaccinations, hourly for
            // appointments (T-24h window).
            $this->app->booted(function () {
                /** @var Schedule $schedule */
                $schedule = $this->app->make(Schedule::class);
                $schedule->command('portal:push:vaccinations')
                    ->dailyAt('08:00')
                    ->withoutOverlapping()
                    ->name('portal-push-vaccinations');
                $schedule->command('portal:push:appointments')
                    ->hourly()
                    ->withoutOverlapping()
                    ->name('portal-push-appointments');
            });
        }
    }

    public function register()
    {
        $this->app->bind(PortalSmsGateway::class, LogSmsGateway::class);

        // Shared registry the per-vertical modules (VetClinic / ClinicCore) plug
        // their public-booking driver into. Singleton so registrations accumulate.
        $this->app->singleton(\Modules\PortalApi\Support\BookingDriverRegistry::class);
    }
}
