<?php

namespace Modules\MedRegistry\Database\Seeders;

use App\Utils\ModuleUtil;
use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\MedRegistry\Entities\MedregModule;
use Modules\MedRegistry\Services\PresetService;

/**
 * Demo data: applies the `polyclinic` preset to the business named
 * 'Shifa One' with optional radiology + every specialty whose module is
 * actually installed on this host, and marks the wizard completed.
 * Skips silently when the business is absent (other host projects).
 */
class MedregDemoSeeder extends Seeder
{
    public function run(): void
    {
        if (! Schema::hasTable('medreg_modules')
            || ! Schema::hasTable('medreg_business_types')
            || ! Schema::hasTable('business')) {
            return;
        }

        $business = DB::table('business')->where('name', 'Shifa One')->first();
        if (empty($business)) {
            return; // not the Shifa host / demo DB — skip silently
        }

        $moduleUtil = new ModuleUtil();

        // Specialty spec_keys matching specialty modules that are present AND
        // installed (system.{module}_version) on this host.
        $specialtyKeys = MedregModule::where('category', 'specialty')
            ->where('is_present', true)
            ->whereNotNull('spec_key')
            ->orderBy('module_key')
            ->get()
            ->filter(function ($m) use ($moduleUtil) {
                return $moduleUtil->isModuleInstalled($m->module_key);
            })
            ->pluck('spec_key')
            ->unique()
            ->values()
            ->all();

        $selected = array_merge(['radiology'], $specialtyKeys);

        $userId = DB::table('users')
            ->where('business_id', $business->id)
            ->orderBy('id')
            ->value('id');

        $report = app(PresetService::class)->apply(
            (int) $business->id,
            'polyclinic',
            $selected,
            ! empty($userId) ? (int) $userId : null
        );

        if ($this->command) {
            $this->command->info(sprintf(
                'MedRegistry demo: polyclinic preset applied to "Shifa One" — %d spec modules enabled, %d skipped (no host module), %d dependencies auto-added.',
                count($report['enabled']),
                count($report['skipped_missing']),
                count($report['dependency_added'])
            ));
        }
    }
}
