<?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
{
    private const LEGACY_PRODUCT_VARIANT = 'App\\Domains\\Catalog\\Models\\ProductVariant';

    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('group_items', function (Blueprint $table) {
            $table->nullableMorphs('groupable');
        });

        DB::table('group_items')->update([
            'groupable_type' => self::LEGACY_PRODUCT_VARIANT,
            'groupable_id' => DB::raw('product_variant_id'),
        ]);

        $productVariantForeignKey = collect(Schema::getForeignKeys('group_items'))
            ->first(fn (array $foreignKey): bool => $foreignKey['columns'] === ['product_variant_id']);

        Schema::table('group_items', function (Blueprint $table) use ($productVariantForeignKey) {
            if ($productVariantForeignKey !== null) {
                $table->dropForeign($productVariantForeignKey['name']);
            }

            $table->dropColumn('product_variant_id');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        if (DB::table('group_items')->where('groupable_type', '!=', self::LEGACY_PRODUCT_VARIANT)->exists()) {
            throw new RuntimeException('Cannot roll back groupable group items while bundle items exist.');
        }

        Schema::table('group_items', function (Blueprint $table) {
            $table->unsignedBigInteger('product_variant_id')->nullable();
        });

        DB::table('group_items')->update([
            'product_variant_id' => DB::raw('groupable_id'),
        ]);

        Schema::table('group_items', function (Blueprint $table) {
            $table->dropMorphs('groupable');
            $table->foreign('product_variant_id')
                ->references('id')
                ->on('productos_variantes')
                ->cascadeOnDelete();
        });
    }
};
