<?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('catalog_items')
            ->join('event_dates', function ($join): void {
                $join->on('event_dates.tenant_code', '=', 'catalog_items.tenant_code')
                    ->on('event_dates.validity_time_id', '=', 'catalog_items.validity_time_id');
            })
            ->whereNotNull('catalog_items.validity_time_id')
            ->select([
                'catalog_items.id as catalog_item_id',
                'event_dates.id as event_date_id',
            ])
            ->orderBy('catalog_items.id')
            ->orderBy('event_dates.id')
            ->each(function (object $association): void {
                $variantIds = DB::table('variantes')
                    ->where('catalog_item_id', $association->catalog_item_id)
                    ->pluck('id');

                if ($variantIds->isEmpty()) {
                    return;
                }

                DB::table('variantes')
                    ->whereIn('id', $variantIds)
                    ->whereNull('event_date_id')
                    ->update(['event_date_id' => $association->event_date_id]);

                DB::table('variant_event_dates')->insertOrIgnore(
                    $variantIds->map(fn (int $variantId): array => [
                        'variant_id' => $variantId,
                        'event_date_id' => $association->event_date_id,
                    ])->all()
                );
            });

        Schema::table('catalog_items', function (Blueprint $table): void {
            if (DB::getDriverName() !== 'sqlite') {
                $table->dropForeign(['validity_time_id']);
            }

            $table->dropColumn('validity_time_id');
        });
    }

    public function down(): void
    {
        Schema::table('catalog_items', function (Blueprint $table): void {
            $table->foreignId('validity_time_id')
                ->nullable()
                ->after('has_tickets')
                ->constrained('validity_times')
                ->cascadeOnUpdate()
                ->nullOnDelete();
        });
    }
};
