<?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
{
    /**
     * international_tour_dates.assigned_guide_id / assigned_vehicle_id kolonları
     * yanlışlıkla `definitions` tablosuna FK'li oluşturulmuştu (eski kalıp kopyalanmış).
     * Cultural/day_trip'te bu kolonlar `resources`'a bağlı; operasyon kaynak ataması
     * buraya resource id yazdığı için tutarlı olması gerekiyor. FK'i resources'a taşı.
     */
    public function up(): void
    {
        // Olası artık (definitions'a ait) değerleri temizle — resources'ta olmayanları null yap.
        $resourceIds = DB::table('resources')->pluck('id')->all();
        DB::table('international_tour_dates')
            ->whereNotNull('assigned_guide_id')
            ->when($resourceIds, fn ($q) => $q->whereNotIn('assigned_guide_id', $resourceIds))
            ->update(['assigned_guide_id' => null]);
        DB::table('international_tour_dates')
            ->whereNotNull('assigned_vehicle_id')
            ->when($resourceIds, fn ($q) => $q->whereNotIn('assigned_vehicle_id', $resourceIds))
            ->update(['assigned_vehicle_id' => null]);

        Schema::table('international_tour_dates', function (Blueprint $table) {
            foreach (['assigned_guide_id', 'assigned_vehicle_id'] as $col) {
                try {
                    $table->dropForeign([$col]);
                } catch (\Throwable $e) {
                    // FK yoksa yok say
                }
            }
        });

        Schema::table('international_tour_dates', function (Blueprint $table) {
            $table->foreign('assigned_guide_id')->references('id')->on('resources')->onDelete('set null');
            $table->foreign('assigned_vehicle_id')->references('id')->on('resources')->onDelete('set null');
        });
    }

    public function down(): void
    {
        Schema::table('international_tour_dates', function (Blueprint $table) {
            foreach (['assigned_guide_id', 'assigned_vehicle_id'] as $col) {
                try {
                    $table->dropForeign([$col]);
                } catch (\Throwable $e) {
                }
            }
        });

        Schema::table('international_tour_dates', function (Blueprint $table) {
            $table->foreign('assigned_guide_id')->references('id')->on('definitions')->onDelete('set null');
            $table->foreign('assigned_vehicle_id')->references('id')->on('definitions')->onDelete('set null');
        });
    }
};
