<?php

namespace Modules\MedDocuments\Providers;

use Illuminate\Database\Eloquent\Factory;
use Illuminate\Support\ServiceProvider;
use Modules\MedDocuments\Services\MedDocuments;

/**
 * MedDocuments module bootstrap. Mirrors VrcServiceProvider / MedRegistry.
 *
 * The documents service (Modules\MedDocuments\Services\MedDocuments) is the
 * public attach/retrieve API other modules call. It is registered as a
 * singleton and also aliased `meddocuments` so callers can use either
 * app(MedDocuments::class) or app('meddocuments').
 */
class MedDocumentsServiceProvider extends ServiceProvider
{
    protected string $moduleName = 'MedDocuments';

    protected string $moduleNameLower = 'meddocuments';

    public function boot(): void
    {
        $this->publishes([
            __DIR__ . '/../Config/config.php' => config_path('meddocuments.php'),
        ], 'config');

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

    /**
     * Register a private `meddoc` filesystem disk (additively — core
     * filesystems.php is never touched) rooted OFF the public web root. Used as
     * the fallback store when SmartStorage is not installed, so medical
     * documents are never reachable by a guessable /uploads/... URL and always
     * flow through the audited/watermarked controller routes.
     */
    protected function registerPrivateDisk(): void
    {
        if (empty(config('filesystems.disks.meddoc'))) {
            config([
                'filesystems.disks.meddoc' => [
                    'driver'     => 'local',
                    // Root at storage/app: stored paths already carry the
                    // meddocs/{business}/{doc} prefix, which namespaces the
                    // folder without doubling it.
                    'root'       => config('meddocuments.private_root', storage_path('app')),
                    'visibility' => 'private',
                    'throw'      => false,
                ],
            ]);
        }
    }

    public function register(): void
    {
        $this->mergeConfigFrom(__DIR__ . '/../Config/config.php', 'meddocuments');
        $this->app->register(RouteServiceProvider::class);

        // The shared documents service — the public API for every module.
        $this->app->singleton(MedDocuments::class, fn () => new MedDocuments());
        $this->app->alias(MedDocuments::class, 'meddocuments');
    }

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

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

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

    public function registerTranslations(): void
    {
        $langPath = resource_path('lang/modules/' . $this->moduleNameLower);

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

    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 [MedDocuments::class, 'meddocuments'];
    }
}
