<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // The cart_id foreign key is supported only by the composite unique index,
        // so give it a standalone index before the unique is dropped. (product_id
        // already has its own FK index.)
        $hasCartIdIndex = collect(DB::select('SHOW INDEX FROM cart_items'))
            ->contains(fn ($r) => $r->Key_name === 'cart_items_cart_id_index');

        if (! $hasCartIdIndex) {
            Schema::table('cart_items', function (Blueprint $table) {
                $table->index('cart_id', 'cart_items_cart_id_index');
            });
        }

        // Clean up a redundant index left behind by an earlier failed attempt.
        $hasStrayProductIndex = collect(DB::select('SHOW INDEX FROM cart_items'))
            ->contains(fn ($r) => $r->Key_name === 'cart_items_product_id_index');

        if ($hasStrayProductIndex) {
            Schema::table('cart_items', function (Blueprint $table) {
                $table->dropIndex('cart_items_product_id_index');
            });
        }

        Schema::table('cart_items', function (Blueprint $table) {
            $table->dropUnique('cart_items_cart_id_product_id_unique');
        });

        Schema::table('cart_items', function (Blueprint $table) {
            $table->foreignId('product_variant_id')
                ->nullable()
                ->after('product_id')
                ->constrained('product_variants')
                ->cascadeOnDelete();

            $table->unique(['cart_id', 'product_id', 'product_variant_id'], 'cart_items_cart_product_variant_unique');
        });
    }

    public function down(): void
    {
        Schema::table('cart_items', function (Blueprint $table) {
            $table->dropUnique('cart_items_cart_product_variant_unique');
            $table->dropConstrainedForeignId('product_variant_id');
            $table->unique(['cart_id', 'product_id'], 'cart_items_cart_id_product_id_unique');
            $table->dropIndex('cart_items_cart_id_index');
        });
    }
};
