<?php

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

/**
 * mbb_issues — a bag issued for transfusion + its transfusion / reaction record.
 *
 * A crossmatch (compatible) gates issuance. On transfusion a reaction may be
 * recorded, which flags the issue and raises a ClinicCore MedicalAlertService
 * CRITICAL alert (patient-linked, idempotent per issue — see BloodBankService).
 *
 * crossmatch_id → mbb_crossmatches.id, donation_id → mbb_donations.id,
 * patient_id → clc_patients.id. business_id-scoped.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mbb_issues')) {
            return;
        }

        Schema::create('mbb_issues', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedBigInteger('crossmatch_id');
            $t->unsignedBigInteger('donation_id');
            $t->unsignedInteger('patient_id');            // clc_patients.id (recipient)
            $t->enum('issued_to', ['or', 'ward', 'er', 'other'])->default('ward');
            $t->unsignedBigInteger('issued_by')->nullable();      // users.id
            $t->timestamp('issued_at')->nullable();
            $t->timestamp('transfusion_started_at')->nullable();
            $t->timestamp('transfusion_completed_at')->nullable();
            $t->unsignedBigInteger('transfused_by')->nullable();  // users.id
            $t->boolean('reaction')->default(false);
            $t->enum('reaction_type', ['febrile', 'allergic', 'hemolytic', 'taco', 'trali', 'other'])->nullable();
            $t->enum('reaction_severity', ['mild', 'moderate', 'severe', 'life_threatening'])->nullable();
            $t->text('reaction_management')->nullable();
            $t->enum('status', ['issued', 'transfusing', 'completed', 'returned'])->default('issued');
            $t->timestamps();

            $t->index(['business_id', 'status'], 'mbb_issues_biz_status_idx');
            $t->index(['business_id', 'patient_id'], 'mbb_issues_biz_patient_idx');
            $t->index(['business_id', 'donation_id'], 'mbb_issues_biz_donation_idx');
            $t->index('crossmatch_id', 'mbb_issues_xm_idx');
        });
    }

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