<?php

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

/**
 * Links each topping/inner-option item to its inventory source so that
 * when a customer selects it on an order, the correct stock is deducted.
 *
 * Two types of toppings:
 *   1. Raw ingredient  (sprinkles, nuts, cherry) → deduct from stock_ledger
 *   2. Produced daily  (Lotus syrup, Nutella, brownie) → deduct from production_batch
 *
 * Only one of ingredient_id or source_product_id should be set per item.
 * deduction_grams = how many grams to deduct from inventory per 1 use.
 */
return new class extends Migration
{
    public function up(): void
    {
        Schema::table('inner_option_items', function (Blueprint $table) {
            // For raw-stock toppings (sprinkles, nuts, wafer, cherry…)
            $table->foreignId('ingredient_id')
                  ->nullable()
                  ->after('sort_order')
                  ->constrained('ingredients')
                  ->nullOnDelete();

            // For daily-production toppings (Lotus syrup, Nutella, brownie pieces…)
            $table->foreignId('source_product_id')
                  ->nullable()
                  ->after('ingredient_id')
                  ->constrained('products')
                  ->nullOnDelete();

            // Grams to deduct per single use of this topping
            $table->decimal('deduction_grams', 8, 2)
                  ->default(0)
                  ->after('source_product_id')
                  ->comment('Grams deducted from stock/batch per 1 topping use');
        });
    }

    public function down(): void
    {
        Schema::table('inner_option_items', function (Blueprint $table) {
            $table->dropForeign(['ingredient_id']);
            $table->dropForeign(['source_product_id']);
            $table->dropColumn(['ingredient_id', 'source_product_id', 'deduction_grams']);
        });
    }
};
