<?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
    {
        Schema::create('ticket_validity_times', function (Blueprint $table): void {
            $table->foreignId('ticket_id')
                ->constrained('tickets')
                ->cascadeOnUpdate()
                ->cascadeOnDelete();
            $table->foreignId('validity_time_id')
                ->constrained('validity_times')
                ->cascadeOnUpdate()
                ->restrictOnDelete();

            $table->primary(['ticket_id', 'validity_time_id']);
        });

        DB::table('ticket_validity_times')->insertUsing(
            ['ticket_id', 'validity_time_id'],
            DB::table('tickets')
                ->select(['id', 'validity_time_id'])
                ->whereNotNull('validity_time_id'),
        );

        Schema::table('tickets', function (Blueprint $table): void {
            $table->dropConstrainedForeignId('validity_time_id');
        });
    }

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

        DB::table('ticket_validity_times')
            ->orderBy('ticket_id')
            ->orderBy('validity_time_id')
            ->get()
            ->groupBy('ticket_id')
            ->each(function ($validityTimes, int|string $ticketId): void {
                DB::table('tickets')
                    ->where('id', $ticketId)
                    ->update([
                        'validity_time_id' => $validityTimes->first()->validity_time_id,
                    ]);
            });

        Schema::dropIfExists('ticket_validity_times');
    }
};
