<?php

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

/**
 * lab_test_sessions — one analyzer run for one sample.
 *
 * `uuid` is generated by the LabBridge Agent and is the idempotency key:
 * replaying a queued message after a lost confirmation updates the same row
 * instead of creating a duplicate.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('lab_test_sessions')) {
            return;
        }

        Schema::create('lab_test_sessions', function (Blueprint $table) {
            $table->increments('id');
            $table->uuid('uuid')->unique()->comment('Agent-generated idempotency key');
            $table->unsignedInteger('business_id')->nullable()->index();
            $table->unsignedInteger('agent_id')->nullable()->index();
            $table->unsignedInteger('device_id')->nullable()->index();
            $table->string('vendor', 30)->index();
            $table->string('sample_no', 30)->index();
            $table->string('patient_id', 30)->nullable()->index();
            $table->string('patient_name', 80)->nullable();
            $table->string('test_condition', 20)->default('NORMAL')->comment('NORMAL / CONTROL');
            $table->date('test_date')->nullable();
            $table->time('test_time')->nullable();
            $table->string('sample_type', 20)->nullable();
            $table->string('species', 40)->nullable();
            $table->string('species_code', 10)->nullable();
            $table->string('sex', 10)->nullable();
            $table->unsignedSmallInteger('age')->nullable();
            $table->string('operator_id', 30)->nullable();
            $table->string('analyzer_id', 30)->nullable();
            $table->string('device_ip', 45)->nullable();
            $table->enum('source', ['agent', 'manual', 'api'])->default('agent');
            $table->json('meta')->nullable()->comment('Vendor-specific extras (slide lot, comm type, position...)');
            // VetClinic sync linkage
            $table->unsignedInteger('contact_id')->nullable()->index();
            $table->unsignedInteger('vc_pet_id')->nullable()->index();
            $table->timestamps();

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

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