<?php

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

/**
 * medsx_cases — a surgical case (SIFA spec §16 surgery > surgical_case). REUSE:
 *   - patient_id / contact_id  → ClinicCore clc_patients (int PK)
 *   - appointment_id           → ClinicCore clc_appointments (type=surgery)
 *   - primary_surgeon_id / scrub_nurse_id / circulating_nurse_id → clc_doctors
 *   - or_room_id               → MedOrganization org_rooms (room_type=operating,
 *                                bigIncrements PK → unsignedBigInteger here)
 *   - consent_id               → ClinicCore clc_consents (the consent gate link)
 *
 * No FK constraints to the reuse tables: those live in other (optional) modules,
 * so the columns are plain nullable integers guarded at the application layer.
 * business_id everywhere; status transitions run through SurgeryService.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('medsx_cases')) {
            return;
        }

        Schema::create('medsx_cases', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->string('case_no', 60);                              // SX-{biz}-{seq}

            // Patient (ClinicCore, int PK).
            $t->unsignedInteger('patient_id');
            $t->unsignedInteger('contact_id')->nullable();
            $t->unsignedInteger('appointment_id')->nullable();     // clc_appointments (type surgery)

            // Team.
            $t->unsignedInteger('primary_surgeon_id')->nullable(); // clc_doctors
            $t->json('assistant_ids')->nullable();                 // [clc_doctors.id]
            $t->string('anesthetist_name', 191)->nullable();
            $t->unsignedInteger('scrub_nurse_id')->nullable();     // clc_doctors
            $t->unsignedInteger('circulating_nurse_id')->nullable(); // clc_doctors

            // Procedure detail.
            $t->json('procedures')->nullable();                    // [{name, cpt_code, laterality}]
            $t->text('diagnosis')->nullable();
            $t->unsignedTinyInteger('asa_class')->nullable();      // 1-6
            $t->enum('priority', ['elective', 'urgent', 'emergency'])->default('elective');
            $t->enum('anesthesia_type', [
                'general', 'spinal', 'epidural', 'regional', 'local', 'sedation', 'combined',
            ])->nullable();

            // Scheduling (OR room = org_rooms bigIncrements → bigInteger).
            $t->unsignedBigInteger('or_room_id')->nullable();
            $t->date('scheduled_date')->nullable();
            $t->dateTime('scheduled_start')->nullable();
            $t->dateTime('scheduled_end')->nullable();
            $t->dateTime('actual_start')->nullable();
            $t->dateTime('actual_end')->nullable();

            // Consent gate.
            $t->unsignedInteger('consent_id')->nullable();         // clc_consents

            // Intra/post-op record.
            $t->text('findings')->nullable();
            $t->text('complications')->nullable();
            $t->json('specimens')->nullable();                     // [{description, sent_to, lab_number}]
            $t->json('implants')->nullable();                      // [{name, serial, lot}]
            $t->enum('blood_loss', ['minimal', 'moderate', 'significant', 'massive'])->nullable();

            $t->enum('status', [
                'scheduled', 'pre_op', 'in_or', 'post_op', 'completed', 'cancelled', 'postponed',
            ])->default('scheduled');
            $t->string('cancellation_reason', 255)->nullable();

            $t->unsignedInteger('created_by')->nullable();
            $t->timestamps();

            $t->unique(['business_id', 'case_no'], 'medsx_cases_biz_no_uq');
            $t->index(['business_id', 'status'], 'medsx_cases_biz_status_idx');
            $t->index(['business_id', 'patient_id'], 'medsx_cases_biz_patient_idx');
            $t->index(['business_id', 'or_room_id', 'scheduled_date'], 'medsx_cases_biz_room_date_idx');
            $t->index(['business_id', 'scheduled_date'], 'medsx_cases_biz_date_idx');
        });
    }

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