<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('nx_test_results')) {
            return;
        }

        Schema::create('nx_test_results', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('test_session_id');
            $table->string('test_name', 10)->index()->comment('e.g. GLU-P, ALB-W');
            $table->string('base_name', 8)->nullable()->comment('Test name without sample type suffix');
            $table->string('sample_suffix', 3)->nullable()->comment('-W, -P, -U or empty');
            $table->string('equality', 1)->default('=')->comment('= > < *');
            $table->string('result', 20)->nullable()->comment('Numeric or special: +, -, -OR, ****, E, EXP, CHK QC');
            $table->string('unit', 8)->nullable()->comment('e.g. mg/dl');
            $table->unsignedTinyInteger('dilution_factor')->default(1);
            $table->string('ref_lower', 5)->nullable()->comment('Reference range lower bound');
            $table->string('ref_upper', 5)->nullable()->comment('Reference range upper bound');
            // Warning flags (11 positions)
            $table->boolean('warn_high')->default(false)->comment('H: above upper reference limit');
            $table->boolean('warn_low')->default(false)->comment('L: below lower reference limit');
            $table->boolean('warn_out_of_range')->default(false)->comment('@: outside determination range');
            $table->boolean('warn_slide_expired')->default(false)->comment('#: slide valid term expired');
            $table->boolean('warn_temp_error')->default(false)->comment('$: temperature control error');
            $table->boolean('warn_photometer_error')->default(false)->comment('*/?');
            $table->boolean('warn_high_value')->default(false)->comment('&: abnormally high testing value');
            $table->boolean('warn_calc_error')->default(false)->comment('E: calculation error');
            $table->boolean('warn_unspotted')->default(false)->comment('\\: un-spotted slide');
            $table->string('raw_warning', 11)->nullable()->comment('Raw 11-char warning string');
            $table->boolean('is_abnormal')->default(false)->comment('Any abnormal flag active');
            $table->timestamps();

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

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