<?php

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

/**
 * cll_test_catalog_analytes — panel definition + reference / critical ranges.
 *
 * One row per parameter within a catalog test. `analyte_code` maps to the raw
 * vendor code carried on lab_test_results / lab_analyte_map so verification can
 * line the analyzer reading up against the reviewed reference + critical bounds.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('cll_test_catalog_analytes')) {
            return;
        }

        Schema::create('cll_test_catalog_analytes', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('catalog_id')->index();
            $table->string('analyte_code', 40)->index()->comment('Maps lab_analyte_map / vendor analyte code');
            $table->string('analyte_name', 120);
            $table->string('unit', 24)->nullable();
            $table->decimal('ref_low', 12, 4)->nullable();
            $table->decimal('ref_high', 12, 4)->nullable();
            $table->decimal('critical_low', 12, 4)->nullable();
            $table->decimal('critical_high', 12, 4)->nullable();
            $table->unsignedSmallInteger('sort_order')->default(0);
            $table->timestamps();

            $table->index(['catalog_id', 'analyte_code']);
            if (Schema::hasTable('cll_test_catalog')) {
                $table->foreign('catalog_id')->references('id')->on('cll_test_catalog')->cascadeOnDelete();
            }
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('cll_test_catalog_analytes');
    }
};
