<?php

namespace Modules\ClinicLab\Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Modules\ClinicLab\Entities\CllTestCatalog;
use Modules\ClinicLab\Entities\CllTestCatalogAnalyte;
use Modules\ClinicLab\Entities\CllOutreachProvider;
use Modules\ClinicLab\Entities\Services\CatalogService;

/**
 * Demo catalogue for the 'Shifa One' demo business (created by
 * database/seeders/ShifaInstallSeeder). Does NOTHING when that business is
 * absent. Idempotent (updateOrCreate on code). Links product_id by name match
 * to the "laboratory tests" products the ShifaInstallSeeder creates.
 */
class ClinicLabDemoSeeder extends Seeder
{
    public function run(): void
    {
        $business = DB::table('business')->where('name', 'Shifa One')->first();
        if (! $business) {
            return; // guard: demo business not installed
        }
        if (! Schema::hasTable('cll_test_catalog')) {
            return; // module not migrated
        }

        $bizId   = (int) $business->id;
        $catalog = app(CatalogService::class);

        foreach ($this->tests() as $t) {
            // Prefer an exact product-name match against the demo lab products;
            // fall back to a fuzzier synonym match for names that differ slightly.
            $productId = $catalog->findProductIdByName($bizId, $t['product'] ?? $t['name'])
                ?? $catalog->findProductIdByName($bizId, $t['name']);

            $row = CllTestCatalog::updateOrCreate(
                ['business_id' => $bizId, 'code' => $t['code']],
                [
                    'name'             => $t['name'],
                    'category'         => $t['category'],
                    'product_id'       => $productId,
                    'specimen_type'    => $t['specimen_type'] ?? 'blood',
                    'container'        => $t['container'] ?? null,
                    'min_volume'       => $t['min_volume'] ?? null,
                    'fasting_required' => $t['fasting'] ?? false,
                    'tat_hours'        => $t['tat'] ?? 24,
                    'method'           => $t['method'] ?? null,
                    'is_panel'         => ! empty($t['analytes']) && count($t['analytes']) > 1,
                    'is_active'        => true,
                ]
            );

            CllTestCatalogAnalyte::where('catalog_id', $row->id)->delete();
            $sort = 0;
            foreach (($t['analytes'] ?? []) as $a) {
                CllTestCatalogAnalyte::create([
                    'catalog_id'    => $row->id,
                    'analyte_code'  => $a[0],
                    'analyte_name'  => $a[1],
                    'unit'          => $a[2],
                    'ref_low'       => $a[3],
                    'ref_high'      => $a[4],
                    'critical_low'  => $a[5],
                    'critical_high' => $a[6],
                    'sort_order'    => $sort++,
                ]);
            }
        }

        CllOutreachProvider::updateOrCreate(
            ['business_id' => $bizId, 'name' => 'Reference Lab Partners'],
            ['contact_person' => 'Dr. Nour', 'phone' => '+20-100-000-0000',
             'email' => 'reference@labpartners.example', 'is_active' => true]
        );

        if (isset($this->command)) {
            $this->command->info('ClinicLab demo catalogue seeded for Shifa One (business #' . $bizId . ').');
        }
    }

    /**
     * ~10 common tests. `analytes` rows are:
     * [code, name, unit, ref_low, ref_high, critical_low, critical_high].
     * `product` (optional) overrides the name used for the ERP product match.
     */
    protected function tests(): array
    {
        return [
            [
                'code' => 'CBC', 'name' => 'Complete Blood Count', 'category' => 'hematology',
                'product' => 'CBC / Complete Blood Count', 'container' => 'EDTA tube', 'min_volume' => '3ml', 'tat' => 4,
                'analytes' => [
                    ['WBC', 'White Blood Cells', '10^3/uL', 4.0, 11.0, 1.0, 30.0],
                    ['HGB', 'Hemoglobin', 'g/dL', 13.0, 17.0, 7.0, 20.0],
                    ['PLT', 'Platelets', '10^3/uL', 150, 450, 20, 1000],
                ],
            ],
            [
                'code' => 'GLU', 'name' => 'Glucose (Fasting)', 'category' => 'chemistry',
                'product' => 'Comprehensive Metabolic Panel', 'container' => 'Fluoride tube', 'min_volume' => '2ml',
                'fasting' => true, 'tat' => 4,
                'analytes' => [
                    ['GLU', 'Glucose', 'mg/dL', 70, 100, 40, 500],
                ],
            ],
            [
                'code' => 'HBA1C', 'name' => 'HbA1c', 'category' => 'chemistry',
                'product' => 'HbA1c', 'container' => 'EDTA tube', 'min_volume' => '2ml', 'tat' => 24,
                'analytes' => [
                    ['HBA1C', 'Glycated Hemoglobin', '%', 4.0, 5.6, null, 15.0],
                ],
            ],
            [
                'code' => 'LIPID', 'name' => 'Lipid Panel', 'category' => 'chemistry',
                'product' => 'Lipid Profile', 'container' => 'Plain tube', 'min_volume' => '3ml',
                'fasting' => true, 'tat' => 24,
                'analytes' => [
                    ['CHOL', 'Total Cholesterol', 'mg/dL', 0, 200, null, null],
                    ['HDL', 'HDL Cholesterol', 'mg/dL', 40, 60, null, null],
                    ['LDL', 'LDL Cholesterol', 'mg/dL', 0, 130, null, null],
                    ['TRIG', 'Triglycerides', 'mg/dL', 0, 150, null, 1000],
                ],
            ],
            [
                'code' => 'LFT', 'name' => 'Liver Function Test', 'category' => 'chemistry',
                'product' => 'Liver Function Test', 'container' => 'Plain tube', 'min_volume' => '3ml', 'tat' => 24,
                'analytes' => [
                    ['ALT', 'Alanine Aminotransferase', 'U/L', 7, 56, null, null],
                    ['AST', 'Aspartate Aminotransferase', 'U/L', 10, 40, null, null],
                    ['TBIL', 'Total Bilirubin', 'mg/dL', 0.1, 1.2, null, 15.0],
                ],
            ],
            [
                'code' => 'KFT', 'name' => 'Renal Function Test', 'category' => 'chemistry',
                'product' => 'Renal Function Test', 'container' => 'Plain tube', 'min_volume' => '3ml', 'tat' => 24,
                'analytes' => [
                    ['UREA', 'Urea', 'mg/dL', 15, 45, null, null],
                    ['CREA', 'Creatinine', 'mg/dL', 0.6, 1.3, null, 10.0],
                    ['K', 'Potassium', 'mmol/L', 3.5, 5.1, 2.5, 6.5],
                ],
            ],
            [
                'code' => 'TSH', 'name' => 'Thyroid Stimulating Hormone', 'category' => 'hormones',
                'product' => 'Thyroid Panel (TSH/T3/T4)', 'container' => 'Plain tube', 'min_volume' => '2ml', 'tat' => 48,
                'analytes' => [
                    ['TSH', 'TSH', 'mIU/L', 0.4, 4.0, null, null],
                ],
            ],
            [
                'code' => 'URINE', 'name' => 'Urinalysis', 'category' => 'urine',
                'product' => 'Urinalysis', 'specimen_type' => 'urine', 'container' => 'Urine container',
                'min_volume' => '10ml', 'tat' => 4,
                'analytes' => [
                    ['PH', 'pH', '', 4.5, 8.0, null, null],
                    ['SG', 'Specific Gravity', '', 1.005, 1.030, null, null],
                ],
            ],
            [
                'code' => 'CRP', 'name' => 'C-Reactive Protein', 'category' => 'immunology',
                'container' => 'Plain tube', 'min_volume' => '2ml', 'tat' => 24,
                'analytes' => [
                    ['CRP', 'C-Reactive Protein', 'mg/L', 0, 5, null, null],
                ],
            ],
            [
                'code' => 'VITD', 'name' => 'Vitamin D (25-OH)', 'category' => 'chemistry',
                'container' => 'Plain tube', 'min_volume' => '2ml', 'tat' => 72,
                'analytes' => [
                    ['VITD', '25-Hydroxyvitamin D', 'ng/mL', 30, 100, null, null],
                ],
            ],
        ];
    }
}
