<?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
{
    public function up(): void
    {
        DB::table('tickets')
            ->whereNotNull('source_variant_id')
            ->whereNotIn('source_variant_id', DB::table('variantes')->select('id'))
            ->update(['source_variant_id' => null]);

        DB::table('tickets')
            ->whereNotNull('source_catalog_item_id')
            ->whereNotIn('source_catalog_item_id', DB::table('catalog_items')->select('id'))
            ->update(['source_catalog_item_id' => null]);

        Schema::table('tickets', function (Blueprint $table): void {
            $table->foreign('source_catalog_item_id')
                ->references('id')
                ->on('catalog_items')
                ->cascadeOnUpdate()
                ->nullOnDelete();
            $table->foreign('source_variant_id')
                ->references('id')
                ->on('variantes')
                ->cascadeOnUpdate()
                ->nullOnDelete();
        });
    }

    public function down(): void
    {
        Schema::table('tickets', function (Blueprint $table): void {
            $table->dropForeign(['source_catalog_item_id']);
            $table->dropForeign(['source_variant_id']);
        });
    }
};
