<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // No FK on product_variant_id — matches product_id's existing
        // convention on this table. NULL-safe: a non-variant product only
        // ever has one branch_stock row with product_variant_id NULL, so
        // MySQL's NULL-distinct unique index semantics keep
        // (branch, product, NULL) unique.
        Schema::table('branch_stock', function (Blueprint $table) {
            $table->unsignedBigInteger('product_variant_id')->nullable()->after('product_id');
        });

        Schema::table('branch_stock', function (Blueprint $table) {
            // Added before dropping the old unique — branch_id's FK needs an
            // index with branch_id as the leftmost column at all times, and
            // the old composite unique was the only index covering it.
            $table->unique(['branch_id', 'product_id', 'product_variant_id'], 'branch_stock_branch_product_variant_unique');
            $table->index('product_variant_id');
        });

        Schema::table('branch_stock', function (Blueprint $table) {
            $table->dropUnique(['branch_id', 'product_id']);
        });
    }

    public function down(): void
    {
        Schema::table('branch_stock', function (Blueprint $table) {
            $table->unique(['branch_id', 'product_id']);
        });

        Schema::table('branch_stock', function (Blueprint $table) {
            $table->dropUnique('branch_stock_branch_product_variant_unique');
            $table->dropIndex(['product_variant_id']);
            $table->dropColumn('product_variant_id');
        });
    }
};
