<?php

namespace App\Console\Commands;

use Database\Seeders\BarcodesTableSeeder;
use Database\Seeders\CurrenciesTableSeeder;
use Database\Seeders\PermissionsTableSeeder;
use Database\Seeders\ShifaInstallSeeder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

/**
 * One-shot installer for the Shifa One human-medical demo edition.
 *
 * Seeds the global reference tables (currencies / permissions / barcodes) if the
 * target DB is fresh, then builds the full Shifa One dataset (business, locations,
 * RBAC users, accounts, products of every type, patient contacts, ClinicCore data
 * — doctors / patients across specialties / appointments / prescriptions /
 * vaccinations / medical reports, lab results via ClinicLab, care-plan contracts,
 * POS + purchases) via ShifaInstallSeeder.
 *
 * Target a fresh DB without touching the dev one, e.g.:
 *   DB_DATABASE=shifa_one_demo php artisan shifa:install
 */
class ShifaInstall extends Command
{
    protected $signature = 'shifa:install {--fresh : delete the existing Shifa One business first}';

    protected $description = 'Install the Shifa One human-medical demo dataset (business, modules, mock data)';

    public function handle(): int
    {
        $this->info('Shifa One install → DB: '.config('database.connections.'.config('database.default').'.database'));

        // Global reference data (only when the DB is fresh).
        if (DB::table('currencies')->count() === 0) {
            $this->line('  · seeding currencies'); resolve(CurrenciesTableSeeder::class)->run();
        }
        if (DB::table('permissions')->count() === 0) {
            $this->line('  · seeding permissions'); resolve(PermissionsTableSeeder::class)->run();
        }
        if (DB::table('barcodes')->count() === 0) {
            $this->line('  · seeding barcodes'); resolve(BarcodesTableSeeder::class)->run();
        }

        $seeder = resolve(ShifaInstallSeeder::class);
        $seeder->setContainer($this->getLaravel());
        $seeder->setCommand($this);
        $seeder->fresh = (bool) $this->option('fresh');
        $seeder->run();

        $this->newLine();
        $this->info('Shifa One install complete.');

        return self::SUCCESS;
    }
}
