<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // Check if uuid column already exists from previous failed migration
        if (!Schema::hasColumn('orders', 'uuid')) {
            Schema::table('orders', function (Blueprint $table) {
                // Add UUID column
                $table->uuid('uuid')->nullable()->unique()->after('id');
            });
        }
        
        // Populate existing orders with UUIDs
        DB::table('orders')->whereNull('uuid')->update([
            'uuid' => DB::raw('UUID()')
        ]);
        
        // Make UUID non-nullable
        Schema::table('orders', function (Blueprint $table) {
            $table->uuid('uuid')->nullable(false)->change();
        });
        
        // Temporarily disable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=0');
        
        // Drop the foreign key constraint on order_items
        DB::statement('ALTER TABLE `order_items` DROP FOREIGN KEY `order_items_order_id_foreign`');
        
        // Change order_id column in order_items to uuid type first
        // Get the UUID values from orders and map them to order_items
        DB::statement('ALTER TABLE `order_items` MODIFY `order_id` CHAR(36) NULL');
        
        // Update order_items with uuid values from orders
        DB::statement('UPDATE `order_items` oi INNER JOIN `orders` o ON oi.order_id = o.id SET oi.order_id = o.uuid');
        
        // Make order_id non-nullable
        DB::statement('ALTER TABLE `order_items` MODIFY `order_id` CHAR(36) NOT NULL');
        
        // Remove auto_increment from id column, then drop it and make uuid the primary key
        DB::statement('ALTER TABLE `orders` MODIFY `id` INT NOT NULL');
        DB::statement('ALTER TABLE `orders` DROP PRIMARY KEY, ADD PRIMARY KEY (`uuid`)');
        DB::statement('ALTER TABLE `orders` DROP COLUMN `id`');
        
        // Recreate the foreign key constraint on order_items pointing to uuid
        DB::statement('ALTER TABLE `order_items` ADD CONSTRAINT `order_items_order_id_foreign` FOREIGN KEY (`order_id`) REFERENCES `orders`(`uuid`) ON DELETE CASCADE');
        
        // Re-enable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=1');
    }

    public function down(): void
    {
        // Disable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=0');
        
        // Drop the uuid-based foreign key
        DB::statement('ALTER TABLE `order_items` DROP FOREIGN KEY `order_items_order_id_foreign`');
        
        // Check if id column still exists, if not we need to restore it
        if (!Schema::hasColumn('orders', 'id')) {
            Schema::table('orders', function (Blueprint $table) {
                $table->id()->first();
            });
        }
        
        // Convert order_id back to integer and update references
        DB::statement('ALTER TABLE `order_items` MODIFY `order_id` BIGINT UNSIGNED NULL');
        
        // Update order_items with id values from orders
        DB::statement('UPDATE `order_items` oi INNER JOIN `orders` o ON oi.order_id = o.uuid SET oi.order_id = o.id');
        
        // Make order_id non-nullable
        DB::statement('ALTER TABLE `order_items` MODIFY `order_id` BIGINT UNSIGNED NOT NULL');
        
        // Recreate the original foreign key pointing to id
        DB::statement('ALTER TABLE `order_items` ADD CONSTRAINT `order_items_order_id_foreign` FOREIGN KEY (`order_id`) REFERENCES `orders`(`id`) ON DELETE CASCADE');
        
        // Drop uuid column if it exists
        if (Schema::hasColumn('orders', 'uuid')) {
            Schema::table('orders', function (Blueprint $table) {
                $table->dropUnique(['uuid']);
                $table->dropColumn('uuid');
            });
        }
        
        // Re-enable foreign key checks
        DB::statement('SET FOREIGN_KEY_CHECKS=1');
    }
};
