<?php

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

/**
 * SIFA P4-T2 — inventory consumption bridge guard.
 *
 * When a vaccination is administered with a medicine_id whose medicine carries
 * an ERP product_id, ClinicalConsumptionService creates ONE proper ERP stock
 * adjustment (type=stock_adjustment) to decrement the dose from stock. This
 * column records the resulting transactions.id so the bridge is idempotent —
 * a re-save of the same administered vaccination never double-consumes.
 */
class AddConsumedAdjustmentIdToClcVaccinations extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('clc_vaccinations')) return;

        Schema::table('clc_vaccinations', function (Blueprint $table) {
            if (!Schema::hasColumn('clc_vaccinations', 'consumed_adjustment_id')) {
                $table->unsignedInteger('consumed_adjustment_id')->nullable()->after('medicine_id');
            }
        });
    }

    public function down()
    {
        if (!Schema::hasTable('clc_vaccinations')) return;

        Schema::table('clc_vaccinations', function (Blueprint $table) {
            if (Schema::hasColumn('clc_vaccinations', 'consumed_adjustment_id')) {
                $table->dropColumn('consumed_adjustment_id');
            }
        });
    }
}
