<?php

namespace Modules\DentalClinic\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Console\Scheduling\Schedule;
use Modules\DentalClinic\Console\DentalSendRecalls;

/**
 * Thin specialty-plugin provider. DentalClinic is now a ClinicCore plugin: it
 * contributes a dental driver, its tooth-chart extension tables
 * (dental_patient_profiles + dental_tooth_findings) and the Blade fragments
 * ClinicCore injects into its shared patient screens. All clinic UI/workflow
 * lives in ClinicCore.
 */
class DentalClinicServiceProvider extends ServiceProvider
{
    public function boot()
    {
        $this->registerViews();
        $this->registerTranslations();
        $this->loadMigrationsFrom(__DIR__ . '/../Database/Migrations');
        $this->registerSpecialtyDriver();

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

    /** Register the dentalClinic:: translation namespace (additive lang). */
    public function registerTranslations()
    {
        $langPath = __DIR__ . '/../Resources/lang';
        $this->loadTranslationsFrom($langPath, 'dentalClinic');
    }

    /**
     * Schedule the daily recall dispatcher. Mirrors ClinicCore's convention:
     * only schedule in the 'live' env, registered via callAfterResolving so no
     * core Console\Kernel edit is needed.
     */
    protected function registerSchedule(): void
    {
        $this->callAfterResolving(Schedule::class, function (Schedule $schedule) {
            if (config('app.env') !== 'live') {
                return;
            }
            $schedule->command('dental:send-recalls')->dailyAt('08:15');
        });
    }

    public function register()
    {
        //
    }

    /** Register the dentalClinic:: view namespace so ClinicCore can resolve our fragments. */
    public function registerViews()
    {
        $sourcePath = __DIR__ . '/../Resources/views';
        $this->loadViewsFrom(array_merge(array_map(function ($path) {
            return $path . '/modules/dentalClinic';
        }, \Config::get('view.paths')), [$sourcePath]), 'dentalClinic');
    }

    /**
     * Register Dental as a structural specialty with ClinicCore's
     * SpecialtyDriverRegistry. Degrades gracefully if ClinicCore is absent.
     */
    protected function registerSpecialtyDriver(): void
    {
        try {
            if (class_exists(\Modules\ClinicCore\Entities\Services\SpecialtyDriverRegistry::class)) {
                \Modules\ClinicCore\Entities\Services\SpecialtyDriverRegistry::register(
                    new \Modules\DentalClinic\Entities\Drivers\DentalSpecialtyDriver()
                );
            }
        } catch (\Throwable $e) {
            // Never let driver wiring break boot().
        }
    }
}
