<?php

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

return new class extends Migration
{
    /**
     * Add option_set_item_id to recipe_ingredients so that a single recipe
     * can store different ingredient quantities per size option.
     *
     * Example for "Ice Cream Shake":
     *   ingredient=milk, quantity=140, option_set_item_id=NULL    → Regular size
     *   ingredient=milk, quantity=180, option_set_item_id=<large> → Large size
     *
     * When option_set_item_id is NULL  → base / default quantity.
     * When option_set_item_id is set   → quantity for that specific size option.
     */
    public function up(): void
    {
        Schema::table('recipe_ingredients', function (Blueprint $table) {
            // Drop the old unique constraint (recipe_id, ingredient_id)
            $table->dropUnique(['recipe_id', 'ingredient_id']);

            // Add size-option column
            $table->foreignId('option_set_item_id')
                  ->nullable()
                  ->after('ingredient_id')
                  ->constrained('option_set_items')
                  ->nullOnDelete();

            // Index for fast lookup
            $table->index(['recipe_id', 'ingredient_id', 'option_set_item_id'], 'ri_recipe_ingredient_option_idx');
        });
    }

    public function down(): void
    {
        Schema::table('recipe_ingredients', function (Blueprint $table) {
            $table->dropIndex('ri_recipe_ingredient_option_idx');
            $table->dropForeign(['option_set_item_id']);
            $table->dropColumn('option_set_item_id');
            $table->unique(['recipe_id', 'ingredient_id']);
        });
    }
};
