<?php

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

/**
 * Sales order lines pin the lot they were quoted against.
 *
 * Mirrors held_sale_items.stock_batch_id (2026_07_26_000002) and
 * invoice_items.stock_batch_id (2026_07_02_204548): the lot is carried from
 * the order through to the invoice at conversion, so a sales-order sale is
 * priced from — and traced back to — the exact consignment quoted.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('sales_order_items', function (Blueprint $table) {
            $table->foreignId('stock_batch_id')->nullable()->after('unit_id')->constrained('stock_batches')->cascadeOnUpdate()->nullOnDelete();
            $table->index('stock_batch_id');
        });
    }

    public function down(): void
    {
        Schema::table('sales_order_items', function (Blueprint $table) {
            $table->dropIndex(['stock_batch_id']);
            $table->dropConstrainedForeignId('stock_batch_id');
        });
    }
};
