<?php

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

/**
 * mbb_donations — a collected blood bag (spec-level inventory).
 *
 * Each row IS a physical bag: the bag is tracked here in the module table, NOT
 * mirrored as an ERP batch product (a business may choose to do so — see the
 * README — but the module never auto-creates products). `screening` holds the
 * four mandatory infectious-disease markers as JSON, note-referencing the
 * screening samples (ClinicLab cll_specimens convention) rather than a hard FK.
 *
 * expiry_date is auto-derived by BloodBankService::expiryFor() from product_type
 * + collected_at (whole_blood/prbc +35d, ffp/cryo +365d, platelets +5d).
 *
 * business_id-scoped; donor_id → mbb_donors.id.
 */
return new class extends Migration {
    public function up(): void
    {
        if (Schema::hasTable('mbb_donations')) {
            return;
        }

        Schema::create('mbb_donations', function (Blueprint $t) {
            $t->bigIncrements('id');
            $t->unsignedInteger('business_id');
            $t->unsignedBigInteger('donor_id');
            $t->string('bag_no', 60);                     // unique per business
            $t->enum('donation_type', ['voluntary', 'replacement', 'autologous', 'apheresis'])->default('voluntary');
            $t->enum('product_type', ['whole_blood', 'prbc', 'ffp', 'platelets', 'cryo'])->default('whole_blood');
            $t->unsignedInteger('volume_ml')->nullable();
            $t->enum('blood_group', ['A+', 'A-', 'B+', 'B-', 'AB+', 'AB-', 'O+', 'O-']);
            $t->timestamp('collected_at');
            $t->unsignedBigInteger('collected_by')->nullable();   // users.id
            // screening: {hiv, hbv, hcv, syphilis} each negative|reactive|pending
            // (may also carry a note-reference to the ClinicLab specimen no.)
            $t->json('screening')->nullable();
            $t->enum('screening_status', ['pending', 'passed', 'failed'])->default('pending');
            $t->date('expiry_date')->nullable();          // auto-set by the service
            $t->enum('status', [
                'collected', 'quarantined', 'available', 'reserved',
                'issued', 'transfused', 'expired', 'discarded',
            ])->default('collected');
            $t->timestamps();

            $t->unique(['business_id', 'bag_no'], 'mbb_donations_biz_bag_uq');
            $t->index(['business_id', 'status'], 'mbb_donations_biz_status_idx');
            $t->index(['business_id', 'blood_group', 'product_type', 'status'], 'mbb_donations_stock_idx');
            $t->index(['business_id', 'expiry_date'], 'mbb_donations_biz_expiry_idx');
            $t->index('donor_id', 'mbb_donations_donor_idx');
        });
    }

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