<?php

namespace Modules\MedWorkforce\Providers;

use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\ServiceProvider;
use Modules\MedWorkforce\Services\ComplianceService;
use Modules\MedWorkforce\Services\RosterService;

/**
 * MedWorkforce service provider (SIFA plan P7-T1). Mirrors
 * Modules\MedBilling\Providers\MedBillingServiceProvider: views, translations,
 * migrations and the two domain services registered as singletons so the
 * controllers resolve the same instances.
 *
 * This module owns NO console commands — credential expiry alerting already
 * lives in MedOrganization (medorg:license-expiry-alerts); MedWorkforce only
 * reads that data for its compliance dashboard.
 */
class MedWorkforceServiceProvider extends ServiceProvider
{
    /**
     * Boot the application events.
     */
    public function boot(): void
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('medworkforce.php'),
        ], 'config');

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

    /**
     * Register the service provider.
     */
    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../Config/config.php', 'medworkforce');
        $this->app->register(RouteServiceProvider::class);

        $this->app->singleton(RosterService::class, fn ($app) => new RosterService());
        $this->app->singleton(ComplianceService::class, fn ($app) => new ComplianceService());
    }

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

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

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

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

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

    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 [];
    }
}
