<?php

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

/**
 * SIFA P3-T1 — structured allergy list (spec §7 patient > clinical_baseline >
 * known_allergies). Replaces the legacy free-text clc_patients.allergies field
 * with proper typed/severity/source rows. The free-text column stays as a
 * legacy display and is NOT dropped.
 */
class CreateClcPatientAllergiesTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_patient_allergies')) {
            return;
        }

        Schema::create('clc_patient_allergies', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('patient_id');
            $table->string('allergen');
            $table->enum('type', ['drug', 'food', 'environmental', 'latex', 'other'])->default('other');
            $table->enum('severity', ['mild', 'moderate', 'severe', 'life_threatening'])->default('mild');
            $table->text('reaction')->nullable();
            $table->enum('source', ['patient_reported', 'test_confirmed', 'clinical_observation'])->default('patient_reported');
            $table->unsignedInteger('verified_by')->nullable();     // users.id
            $table->timestamp('verified_at')->nullable();
            $table->enum('status', ['active', 'inactive'])->default('active');
            $table->text('notes')->nullable();
            $table->unsignedInteger('created_by')->nullable();      // users.id
            $table->timestamps();

            $table->foreign('business_id')->references('id')->on('business')->onDelete('cascade');
            $table->foreign('patient_id')->references('id')->on('clc_patients')->onDelete('cascade');
            $table->index(['business_id', 'patient_id']);
            $table->index(['patient_id', 'status']);
        });
    }

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