<?php

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

/**
 * lab_test_results — one analyte reading within a session.
 *
 * Vendor-specific warning/flag detail is kept in the `flags` JSON column so a
 * single schema serves NX600 (warn_high/warn_low...) and ASTM (H/L/HH/LL...)
 * alike; `is_abnormal` is the normalized roll-up used by the UI.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('lab_test_results')) {
            return;
        }

        Schema::create('lab_test_results', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('test_session_id');
            $table->string('analyte_code', 20)->index()->comment('Raw vendor code, e.g. GLU-P');
            $table->string('analyte_name', 60)->nullable()->comment('Canonical name from lab_analyte_map');
            $table->string('base_name', 20)->nullable();
            $table->string('sample_suffix', 5)->nullable();
            $table->string('equality', 3)->default('=');
            $table->string('value', 30)->nullable()->comment('Numeric or special (+, -, ****, EXP...)');
            $table->string('unit', 16)->nullable();
            $table->unsignedSmallInteger('dilution_factor')->default(1);
            $table->string('ref_lower', 16)->nullable();
            $table->string('ref_upper', 16)->nullable();
            $table->string('raw_flag', 24)->nullable()->comment('Raw warning/flag string from the device');
            $table->json('flags')->nullable()->comment('Parsed vendor-specific flag set');
            $table->boolean('is_abnormal')->default(false);
            $table->timestamps();

            $table->foreign('test_session_id')->references('id')->on('lab_test_sessions')->cascadeOnDelete();
            $table->index(['test_session_id', 'analyte_code']);
        });
    }

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