<?php

namespace Modules\ClinicStaffPortal\Providers;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Routing\Router;
use Illuminate\Support\ServiceProvider;
use Modules\ClinicStaffPortal\Console\BuildStaffPwaCommand;
use Modules\ClinicStaffPortal\Console\PushStaffUpdatesCommand;
use Modules\ClinicStaffPortal\Console\PushStaffTestCommand;
use Modules\ClinicStaffPortal\Http\Middleware\StaffAuth;

/**
 * Staff/Doctor PWA module.
 *
 * Mirrors the pet-owner stack (PortalApi + pwa-owner) but targets ERP staff:
 *   - Token auth over the existing `users` table (NOT a parallel account store).
 *   - JSON API under /api/v1/staff/*  (Routes/web.php).
 *   - Installable PWA shell served at /staff-app/*  (built from pwa-staff/).
 *
 * Permissions are the existing clinic.* / vet_admission.* set — the staff
 * app never grants more than the user already has in the ERP.
 */
class ClinicStaffPortalServiceProvider extends ServiceProvider
{
    public function boot(Router $router)
    {
        $this->loadViewsFrom(__DIR__ . '/../Resources/views', 'clinicStaffPortal');
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->loadTranslationsFrom(__DIR__ . '/../Resources/lang', 'clinicStaffPortal');
        $this->mergeConfigFrom(__DIR__ . '/../Config/config.php', 'clinicstaffportal');

        // Bearer-token guard for the staff API. Resolves the token to an ERP
        // user and logs them in for the duration of the request so the usual
        // $user->can(...) permission checks + business scoping just work.
        $router->aliasMiddleware('staff-api.auth', StaffAuth::class);

        if ($this->app->runningInConsole()) {
            $this->commands([
                BuildStaffPwaCommand::class,
                PushStaffUpdatesCommand::class,
                PushStaffTestCommand::class,
            ]);

            // Push new ward alerts to staff devices every 15 min (live only),
            // matching PortalApi's scheduling convention.
            $this->app->booted(function () {
                if (config('app.env') !== 'live') return;
                /** @var Schedule $schedule */
                $schedule = $this->app->make(Schedule::class);
                $schedule->command('staff-portal:push-updates')
                    ->everyFifteenMinutes()
                    ->withoutOverlapping()
                    ->name('staff-portal-push-updates');
            });
        }
    }

    public function register()
    {
        //
    }
}
