<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('carrito_items', function (Blueprint $table) {
            $table->string('buyable_type')->nullable();
            $table->unsignedBigInteger('buyable_id')->nullable();
            $table->index('cart_id');
        });

        // Copy existing data
        DB::table('carrito_items')->update([
            'buyable_type' => 'App\Domains\Catalog\Models\ProductVariant',
            'buyable_id' => DB::raw('producto_variante_id'),
        ]);

        Schema::table('carrito_items', function (Blueprint $table) {
            $table->dropForeign(['producto_variante_id']);
        });

        Schema::table('carrito_items', function (Blueprint $table) {
            $table->dropUnique(['cart_id', 'producto_variante_id']);
            $table->dropColumn('producto_variante_id');
            $table->unique(['cart_id', 'buyable_type', 'buyable_id']);
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('carrito_items', function (Blueprint $table) {
            $table->dropUnique(['cart_id', 'buyable_type', 'buyable_id']);
            $table->foreignId('producto_variante_id')->nullable()->constrained('productos_variantes')->onDelete('cascade');
        });

        DB::table('carrito_items')->update([
            'producto_variante_id' => DB::raw('buyable_id'),
        ]);

        Schema::table('carrito_items', function (Blueprint $table) {
            $table->dropColumn(['buyable_type', 'buyable_id']);
            $table->dropIndex(['cart_id']);
            $table->unique(['cart_id', 'producto_variante_id']);
        });
    }
};
