<?php

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

/**
 * lab_devices — a physical analyzer registered against an agent. Connection
 * settings are edited in the cloud UI and pulled down by the agent.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('lab_devices')) {
            return;
        }

        Schema::create('lab_devices', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->nullable()->index();
            $table->unsignedInteger('agent_id')->nullable()->index()->comment('Hosting LabBridge Agent');
            $table->string('vendor', 30)->index()->comment('Driver key: nx600, abaxis, idexx');
            $table->string('model', 60)->nullable();
            $table->string('name', 120)->comment('Display label');
            $table->enum('connection_type', ['tcp', 'serial', 'serial2eth'])->default('tcp');
            $table->string('comm_protocol', 40)->nullable()->comment('e.g. astm-e1394, nx600-type-1');
            // TCP / serial-to-Ethernet
            $table->string('host', 45)->nullable();
            $table->unsignedInteger('port')->nullable();
            // Serial RS-232
            $table->string('com_port', 20)->nullable()->comment('e.g. COM3');
            $table->unsignedInteger('baud')->nullable();
            $table->string('parity', 10)->nullable();
            $table->unsignedTinyInteger('data_bits')->nullable();
            $table->unsignedTinyInteger('stop_bits')->nullable();
            $table->enum('status', ['online', 'offline', 'disabled'])->default('offline');
            $table->timestamp('last_seen_at')->nullable();
            $table->json('settings')->nullable();
            $table->timestamps();

            $table->index(['business_id', 'vendor']);
        });
    }

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