<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    /**
     * Run the migrations.
     * Revert product variations system - drop all variant-related tables and columns
     */
    public function up(): void
    {
        // Drop variant-related columns from order_items
        if (Schema::hasTable('order_items')) {
            Schema::table('order_items', function (Blueprint $table) {
                if (Schema::hasColumn('order_items', 'product_variant_id')) {
                    $table->dropForeign(['product_variant_id']);
                    $table->dropColumn('product_variant_id');
                }
                if (Schema::hasColumn('order_items', 'image_snapshot')) {
                    $table->dropColumn('image_snapshot');
                }
            });
        }

        // Drop variant-related columns from cart_items
        if (Schema::hasTable('cart_items')) {
            Schema::table('cart_items', function (Blueprint $table) {
                if (Schema::hasColumn('cart_items', 'product_variant_id')) {
                    $table->dropForeign(['product_variant_id']);
                    $table->dropColumn('product_variant_id');
                }
            });
        }

        // Drop variant-related tables in reverse order of dependencies
        if (Schema::hasTable('variant_stock_movements')) {
            Schema::dropIfExists('variant_stock_movements');
        }

        if (Schema::hasTable('product_variant_attribute_value')) {
            Schema::dropIfExists('product_variant_attribute_value');
        }

        if (Schema::hasTable('product_variants')) {
            Schema::dropIfExists('product_variants');
        }

        if (Schema::hasTable('attribute_values')) {
            Schema::dropIfExists('attribute_values');
        }

        if (Schema::hasTable('attributes')) {
            Schema::dropIfExists('attributes');
        }
    }

    /**
     * Reverse the migrations.
     * This would re-create the variant system (not recommended to run)
     */
    public function down(): void
    {
        // Note: This would re-create the entire variant system
        // Only use if you need to restore it
    }
};
