<?php

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

/**
 * SIFA P3-T6 — line items of a unified clinical order (spec §7 orders.items[]).
 * Each item carries the service, laterality and, once results land, a summary +
 * abnormal flag. downstream_type/downstream_id link the item to the row created
 * in the routed-to flow (clc_imaging_requests row or lab_worklist row).
 */
class CreateClcOrderItemsTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_order_items')) return;

        Schema::create('clc_order_items', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('order_id');
            $table->string('service_name', 200);
            $table->string('service_code', 60)->nullable();      // LOINC / CPT / local
            $table->enum('laterality', ['left', 'right', 'bilateral', 'na'])->default('na');
            $table->unsignedSmallInteger('quantity')->default(1);
            $table->timestamp('scheduled_at')->nullable();
            $table->text('result_summary')->nullable();
            $table->enum('abnormal_flag', ['normal', 'high', 'low', 'critical_high', 'critical_low'])->nullable();
            $table->enum('status', ['ordered', 'in_progress', 'resulted', 'cancelled'])->default('ordered');
            $table->string('downstream_type', 60)->nullable();   // e.g. clc_imaging_requests / lab_worklist
            $table->unsignedInteger('downstream_id')->nullable();
            $table->string('note', 255)->nullable();             // routing / fail-soft note
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('clc_orders')->onDelete('cascade');
            $table->index('order_id');
        });
    }

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