<?php

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

/**
 * cll_test_catalog — the clinic-facing lab test / panel catalogue (SIFA P4-T4).
 *
 * Lives entirely in ClinicLab: it links an ERP `products` row (pricing/billing)
 * to the specimen requirements + analyte/panel definition that LabCore's device
 * engine has no concept of. LabCore stays a pure analyzer engine; this table is
 * the bridge's own reference data. business_id scoped throughout.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('cll_test_catalog')) {
            return;
        }

        Schema::create('cll_test_catalog', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id')->index();
            $table->string('code', 40)->comment('LOINC or local code — unique per business');
            $table->string('name', 150);
            $table->enum('category', [
                'hematology', 'chemistry', 'microbiology', 'serology', 'immunology',
                'hormones', 'urine', 'stool', 'molecular', 'histopathology', 'other',
            ])->default('other');
            $table->unsignedInteger('product_id')->nullable()->index()
                ->comment('ERP products.id for pricing/billing (nullable — non-billable panels allowed)');
            $table->enum('specimen_type', [
                'blood', 'serum', 'plasma', 'urine', 'stool', 'swab', 'csf', 'tissue', 'other',
            ])->default('blood');
            $table->string('container', 60)->nullable()->comment('e.g. EDTA tube, plain tube');
            $table->string('min_volume', 30)->nullable()->comment('e.g. 5ml');
            $table->boolean('fasting_required')->default(false);
            $table->unsignedSmallInteger('tat_hours')->nullable()->comment('Turnaround time in hours');
            $table->string('method', 120)->nullable();
            $table->boolean('is_panel')->default(false);
            $table->boolean('is_active')->default(true);
            $table->timestamps();

            $table->unique(['business_id', 'code'], 'cll_catalog_biz_code_unique');
            $table->index(['business_id', 'is_active']);
        });
    }

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