<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('compra_items', function (Blueprint $table) {
            $table->string('buyable_type')->nullable();
            $table->unsignedBigInteger('buyable_id')->nullable();
        });

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

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('compra_items', function (Blueprint $table) {
            $table->foreignId('producto_variante_id')->nullable()->constrained('productos_variantes')->onDelete('cascade');
        });

        \Illuminate\Support\Facades\DB::table('compra_items')->update([
            'producto_variante_id' => \Illuminate\Support\Facades\DB::raw('buyable_id'),
        ]);

        Schema::table('compra_items', function (Blueprint $table) {
            $table->dropColumn(['buyable_type', 'buyable_id']);
        });
    }
};
