<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

/**
 * SIFA P5-T5 — diagnostic-center order plugins as data.
 *
 * The diagnostic_center preset (SPEC-INDEX §1) carries optional spec modules
 * ecg_echo / endoscopy / pulmonary_function / audiometry / vision_testing. Rather
 * than build bespoke modules, we expose them as ClinicCore imaging modalities
 * (system defaults, business_id NULL) so diagnostic_center orders route through
 * the SAME imaging request → report pipeline (OrderRoutingService → clc_imaging_
 * requests → clc_imaging_reports).
 *
 * Spec-key → modality mapping (fulfilled here; catalog rows can later resolve via
 * SPEC_ALIASES if needed — see the report NOTE in the module docs):
 *   ecg_echo            → ECG (Electrocardiogram) + ECHO (Echocardiography)
 *   endoscopy           → ENDO   (already seeded by the base imaging migration)
 *   pulmonary_function  → PFT (Pulmonary Function Test)
 *   audiometry          → AUD (Audiometry)
 *   vision_testing      → VIS (Vision Testing)
 *
 * Additive + guarded: each modality is only inserted when its code is absent
 * among the system defaults (business_id NULL). MedRegistry is NOT touched.
 */
class SeedDiagnosticCenterModalities extends Migration
{
    /** [code, name, sort_order] — mirrors the base imaging seed shape. */
    private array $modalities = [
        ['ECG',  'Electrocardiogram (ECG)',       10],
        ['ECHO', 'Echocardiography (ECHO)',       11],
        ['PFT',  'Pulmonary Function Test',       12],
        ['AUD',  'Audiometry',                    13],
        ['VIS',  'Vision Testing',                14],
    ];

    public function up()
    {
        if (!Schema::hasTable('clc_imaging_modalities')) {
            return;
        }

        $now = now();
        foreach ($this->modalities as $m) {
            $exists = DB::table('clc_imaging_modalities')
                ->whereNull('business_id')
                ->where('code', $m[0])
                ->exists();

            if ($exists) {
                continue;
            }

            DB::table('clc_imaging_modalities')->insert([
                'business_id' => null,
                'code'        => $m[0],
                'name'        => $m[1],
                'sort_order'  => $m[2],
                'status'      => 'active',
                'created_at'  => $now,
                'updated_at'  => $now,
            ]);
        }
    }

    public function down()
    {
        if (!Schema::hasTable('clc_imaging_modalities')) {
            return;
        }

        DB::table('clc_imaging_modalities')
            ->whereNull('business_id')
            ->whereIn('code', array_column($this->modalities, 0))
            ->delete();
    }
}
