<?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
    {
        // Add foreign key constraints that are missing
        
        // Cart items foreign keys
        Schema::table('cart_items', function (Blueprint $table) {
            // Check if foreign key doesn't exist before adding
            if (!$this->foreignKeyExists('cart_items', 'cart_items_product_id_foreign')) {
                $table->foreign('product_id')
                      ->references('id')
                      ->on('products')
                      ->onDelete('cascade')
                      ->name('cart_items_product_id_foreign');
            }
        });

        // Order items foreign keys
        Schema::table('order_items', function (Blueprint $table) {
            if (!$this->foreignKeyExists('order_items', 'order_items_product_id_foreign')) {
                $table->foreign('product_id')
                      ->references('id')
                      ->on('products')
                      ->onDelete('restrict')
                      ->name('order_items_product_id_foreign');
            }
        });

        // Stock movements foreign keys
        if (Schema::hasTable('stock_movements')) {
            Schema::table('stock_movements', function (Blueprint $table) {
                if (!$this->foreignKeyExists('stock_movements', 'stock_movements_product_id_foreign')) {
                    $table->foreign('product_id')
                          ->references('id')
                          ->on('products')
                          ->onDelete('cascade')
                          ->name('stock_movements_product_id_foreign');
                }
            });
        }

        // Stock reservations foreign keys
        if (Schema::hasTable('stock_reservations')) {
            Schema::table('stock_reservations', function (Blueprint $table) {
                if (!$this->foreignKeyExists('stock_reservations', 'stock_reservations_product_id_foreign')) {
                    $table->foreign('product_id')
                          ->references('id')
                          ->on('products')
                          ->onDelete('cascade')
                          ->name('stock_reservations_product_id_foreign');
                }
            });
        }

        // Products tax foreign key
        Schema::table('products', function (Blueprint $table) {
            if (!$this->foreignKeyExists('products', 'products_tax_id_foreign')) {
                $table->foreign('tax_id')
                      ->references('id')
                      ->on('taxes')
                      ->onDelete('set null')
                      ->name('products_tax_id_foreign');
            }
        });

        // Products unit foreign key
        Schema::table('products', function (Blueprint $table) {
            if (!$this->foreignKeyExists('products', 'products_unit_id_foreign')) {
                $table->foreign('unit_id')
                      ->references('id')
                      ->on('units')
                      ->onDelete('set null')
                      ->name('products_unit_id_foreign');
            }
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('cart_items', function (Blueprint $table) {
            $table->dropForeign('cart_items_product_id_foreign');
        });

        Schema::table('order_items', function (Blueprint $table) {
            $table->dropForeign('order_items_product_id_foreign');
        });

        if (Schema::hasTable('stock_movements')) {
            Schema::table('stock_movements', function (Blueprint $table) {
                $table->dropForeign('stock_movements_product_id_foreign');
            });
        }

        if (Schema::hasTable('stock_reservations')) {
            Schema::table('stock_reservations', function (Blueprint $table) {
                $table->dropForeign('stock_reservations_product_id_foreign');
            });
        }

        Schema::table('products', function (Blueprint $table) {
            $table->dropForeign('products_tax_id_foreign');
            $table->dropForeign('products_unit_id_foreign');
        });
    }

    /**
     * Check if a foreign key exists
     */
    private function foreignKeyExists(string $table, string $foreignKey): bool
    {
        $connection = Schema::getConnection();
        $driver = $connection->getDriverName();
        
        if ($driver === 'sqlite') {
            return false; // SQLite doesn't support checking foreign keys easily
        }
        
        $databaseName = $connection->getDatabaseName();
        
        try {
            $result = $connection->select(
                "SELECT COUNT(*) as count FROM information_schema.table_constraints 
                 WHERE constraint_schema = ? AND table_name = ? AND constraint_name = ? AND constraint_type = 'FOREIGN KEY'",
                [$databaseName, $table, $foreignKey]
            );
            
            return $result[0]->count > 0;
        } catch (\Exception $e) {
            return false;
        }
    }
};