<?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::create('manufacturing_run_bom_details', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('manufacturing_run_id');
            $table->unsignedBigInteger('ingredient_account_id')->comment('Raw material account ID');
            $table->string('ingredient_name')->comment('Snapshot of ingredient name at time of manufacturing');
            $table->string('ingredient_sku')->comment('Snapshot of ingredient SKU at time of manufacturing');
            $table->decimal('quantity_required', 15, 4)->comment('Quantity required per unit');
            $table->decimal('effective_quantity', 15, 4)->comment('Effective quantity after wastage');
            $table->string('unit')->comment('Unit of measurement');
            $table->string('wastage_type')->comment('Percentage or Absolute');
            $table->decimal('wastage_value', 15, 4)->comment('Wastage value');
            $table->decimal('average_weighted_price', 15, 4)->comment('Snapshot of average weighted price at time of manufacturing');
            $table->decimal('total_cost', 15, 4)->comment('Total cost for this ingredient (effective_quantity * average_weighted_price)');
            $table->timestamps();

            $table->foreign('manufacturing_run_id')->references('id')->on('manufacturing_runs')->onDelete('cascade');
            $table->foreign('ingredient_account_id')->references('id')->on('accounts')->onDelete('cascade');
            $table->index(['manufacturing_run_id', 'ingredient_account_id'], 'mr_bom_details_idx');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('manufacturing_run_bom_details');
    }
};
