<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 1. source_product_id FK'sını drop et (backing index'i olan source_dir_idx'i engelliyor)
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->dropForeign('product_upgrade_paths_source_product_id_foreign');
        });

        // 2. Eski index'leri drop et (unique ve normal — her ikisi de direction kolonunu içeriyor)
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->dropUnique('product_upgrade_paths_unique');
            $table->dropIndex('product_upgrade_paths_source_dir_idx');
        });

        // 3. direction kolonu drop
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->dropColumn('direction');
        });

        // 4. Yeni index + FK yeniden ekle
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            // Source bazlı listeleme için index (FK backing da sağlar)
            $table->index('source_product_id', 'product_upgrade_paths_source_idx');
            // Yeni unique: (source_product_id, target_product_id)
            $table->unique(['source_product_id', 'target_product_id'], 'product_upgrade_paths_unique');
            // FK yeniden
            $table->foreign('source_product_id', 'product_upgrade_paths_source_product_id_foreign')
                  ->references('id')->on('products')->onDelete('cascade');
        });
    }

    public function down(): void
    {
        // 1. Yeni FK'yı drop et
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->dropForeign('product_upgrade_paths_source_product_id_foreign');
        });

        // 2. Yeni index'leri drop et
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->dropUnique('product_upgrade_paths_unique');
            $table->dropIndex('product_upgrade_paths_source_idx');
        });

        // 3. direction kolonunu geri ekle
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->enum('direction', ['upgrade', 'downgrade'])->default('upgrade')->after('target_product_id');
        });

        // 4. Eski index'ler + FK'yı geri ekle
        Schema::table('product_upgrade_paths', function (Blueprint $table) {
            $table->unique(['source_product_id', 'target_product_id', 'direction'], 'product_upgrade_paths_unique');
            $table->index(['source_product_id', 'direction'], 'product_upgrade_paths_source_dir_idx');
            $table->foreign('source_product_id', 'product_upgrade_paths_source_product_id_foreign')
                  ->references('id')->on('products')->onDelete('cascade');
        });
    }
};
