<?php

namespace Modules\MedBilling\Providers;

use Illuminate\Console\Scheduling\Schedule;
use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\ServiceProvider;
use Modules\MedBilling\Console\CaptureCompletedCommand;
use Modules\MedBilling\Services\ChargeCaptureService;
use Modules\MedBilling\Services\ClaimService;

/**
 * MedBilling service provider (SIFA plan P4-T1). Mirrors
 * Modules\MedNotify\Providers\MedNotifyServiceProvider and
 * Modules\MedRegistry: views, translations, migrations, the daily
 * charge-capture console command and its schedule.
 *
 * The two services are registered as singletons so the controllers and the
 * scheduled command resolve the same instances.
 */
class MedBillingServiceProvider extends ServiceProvider
{
    /**
     * Boot the application events.
     */
    public function boot(): void
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('medbilling.php'),
        ], 'config');

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

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

            $this->app->booted(function () {
                /** @var Schedule $schedule */
                $schedule = $this->app->make(Schedule::class);

                // Draft charges for yesterday's completed appointments. Idempotent;
                // safe to run daily. Documented in the README alongside the
                // on-demand "Capture charges" button on the billing worklist.
                $schedule->command('medbill:capture-completed')
                    ->dailyAt('02:00')
                    ->withoutOverlapping()
                    ->name('medbill-capture-completed');
            });
        }
    }

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

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

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

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

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

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

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

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