<?php

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

/**
 * mbb_crossmatches — compatibility testing between a recipient (ClinicCore
 * ClcPatient) and a specific donation bag. Required before a bag may be issued:
 * an `incompatible` result blocks issuance.
 *
 * patient_id → clc_patients.id (recipient, reused — never a parallel table).
 * donation_id → mbb_donations.id. business_id-scoped.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mbb_crossmatches')) {
            return;
        }

        Schema::create('mbb_crossmatches', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedInteger('patient_id');            // clc_patients.id (recipient)
            $t->unsignedBigInteger('donation_id');        // mbb_donations.id
            $t->enum('patient_blood_group', ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-'])->nullable();
            $t->enum('antibody_screen', ['negative', 'positive'])->nullable();
            $t->enum('method', ['gel', 'tube', 'electronic'])->default('tube');
            $t->enum('result', ['compatible', 'incompatible'])->nullable();
            $t->unsignedBigInteger('performed_by')->nullable();   // users.id
            $t->timestamp('performed_at')->nullable();
            $t->unsignedBigInteger('verified_by')->nullable();    // users.id
            $t->timestamps();

            $t->index(['business_id', 'patient_id'], 'mbb_xm_biz_patient_idx');
            $t->index(['business_id', 'donation_id'], 'mbb_xm_biz_donation_idx');
            $t->index(['business_id', 'result'], 'mbb_xm_biz_result_idx');
        });
    }

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