<?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_sessions')) {
            return;
        }

        Schema::create('nx_test_sessions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->nullable()->index();
            $table->string('sample_no', 13)->index();
            $table->string('patient_id', 13)->nullable()->index();
            $table->string('patient_name', 60)->nullable();
            $table->enum('test_condition', ['NORMAL', 'CONTROL'])->default('NORMAL');
            $table->date('test_date');
            $table->time('test_time');
            $table->string('sample_type', 1)->nullable()->comment('W=Whole blood, P=Plasma/Serum, U=Urine');
            $table->tinyInteger('species')->default(0);
            $table->tinyInteger('sex')->default(9)->comment('0=Male, 1=Female, 9=Unknown');
            $table->unsignedSmallInteger('age')->default(999);
            $table->string('sample_position', 2)->default('01');
            // Type A/B extended fields
            $table->string('operator_id', 13)->nullable();
            $table->boolean('emergency_test')->default(false);
            $table->string('analyzer_id', 8)->nullable();
            $table->string('slide_lot', 6)->nullable();
            $table->string('valid_term', 6)->nullable()->comment('YYYYMM format');
            // Communication metadata
            $table->enum('comm_type', ['1', '2', '3', 'A', 'B', '4', 'C'])->default('1');
            $table->string('device_ip', 45)->nullable();
            // VetClinic sync linkage (inherited from the matching worklist entry)
            $table->unsignedInteger('contact_id')->nullable()->index()->comment('VetClinic pet owner contact');
            $table->unsignedInteger('vc_pet_id')->nullable()->index()->comment('VetClinic pet');
            $table->timestamps();

            $table->unique(['sample_no', 'test_date'], 'nx_session_sample_date_unique');
            $table->index(['test_date', 'test_time']);
        });
    }

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