<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('inventory_movements', function (Blueprint $table) {
            // Link to orders (for movements generated by order consumption)
            if (!Schema::hasColumn('inventory_movements', 'order_id')) {
                $table->unsignedBigInteger('order_id')->nullable()->after('inventory_item_id');
                $table->foreign('order_id')
                    ->references('id')
                    ->on('orders')
                    ->onDelete('set null')
                    ->onUpdate('cascade');
            }

            // Link to batch productions (for movements generated by batch production)
            if (!Schema::hasColumn('inventory_movements', 'batch_production_id')) {
                $table->unsignedBigInteger('batch_production_id')->nullable()->after('order_id');
                $table->foreign('batch_production_id')
                    ->references('id')
                    ->on('batch_productions')
                    ->onDelete('set null')
                    ->onUpdate('cascade');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('inventory_movements', function (Blueprint $table) {
            if (Schema::hasColumn('inventory_movements', 'batch_production_id')) {
                $table->dropForeign(['batch_production_id']);
                $table->dropColumn('batch_production_id');
            }
            if (Schema::hasColumn('inventory_movements', 'order_id')) {
                $table->dropForeign(['order_id']);
                $table->dropColumn('order_id');
            }
        });
    }
};


