<?php

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

/**
 * Lot-level pricing + GRN provenance on stock batches.
 *
 * Every confirmed GRN line now creates one stock batch for every product
 * (regardless of tracking mode), and the batch — not the product — owns the
 * selling price. These columns are the additive half of that change:
 *
 *  - sale_price: the price this consignment sells at (the product-level
 *    sale_price column is dropped later, in the destructive migration)
 *  - grn_item_id / grn_id: provenance back to the receipt that created the
 *    lot. grn_id is denormalised so the POS lot picker can group lots by
 *    receipt without joining through grn_items.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('stock_batches', function (Blueprint $table) {
            $table->decimal('sale_price', 12, 2)->nullable()->after('batch_cost');
            $table->foreignId('grn_item_id')->nullable()->after('sale_price')->constrained('grn_items')->cascadeOnUpdate()->nullOnDelete();
            $table->foreignId('grn_id')->nullable()->after('grn_item_id')->constrained('grns')->cascadeOnUpdate()->nullOnDelete();

            // The POS grid and the lot picker both filter by
            // (product_id, branch_id, status_id).
            $table->index(['product_id', 'branch_id', 'status_id']);
        });
    }

    public function down(): void
    {
        Schema::table('stock_batches', function (Blueprint $table) {
            $table->dropIndex(['product_id', 'branch_id', 'status_id']);
            $table->dropConstrainedForeignId('grn_id');
            $table->dropConstrainedForeignId('grn_item_id');
            $table->dropColumn('sale_price');
        });
    }
};
