<?php

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

/**
 * SIFA P3-T2 — structured encounter diagnoses (spec §7 encounter.diagnosis[]).
 * One row per diagnosis captured in the consult screen's assessment area.
 * ICD-10 code is optional (free-text description is the source of truth for
 * clinics that don't code). A diagnosis can be promoted into the longitudinal
 * problem list (clc_patient_conditions) via the "add to problem list" action.
 */
class CreateClcAppointmentDiagnosesTable extends Migration
{
    public function up()
    {
        if (Schema::hasTable('clc_appointment_diagnoses')) return;

        Schema::create('clc_appointment_diagnoses', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('business_id');
            $table->unsignedInteger('appointment_id');
            $table->unsignedInteger('patient_id');
            $table->string('icd_code', 20)->nullable();
            $table->string('description', 255);
            $table->enum('diagnosis_type', ['primary', 'secondary', 'differential'])->default('primary');
            $table->enum('confidence', ['confirmed', 'probable', 'possible'])->default('confirmed');
            $table->unsignedInteger('diagnosed_by')->nullable();   // users.id
            $table->timestamps();

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

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