<?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::table('event_dates', function (Blueprint $table): void {
            $table->unsignedBigInteger('validity_time_id')
                ->nullable()
                ->unique()
                ->after('id');
        });

        DB::table('event_dates')
            ->orderBy('id')
            ->each(function (object $eventDate): void {
                $startsAt = $eventDate->date.' '.$eventDate->time_start;
                $expiresAt = $eventDate->date.' '.$eventDate->time_end;

                if (strtotime($expiresAt) <= strtotime($startsAt)) {
                    $expiresAt = date('Y-m-d H:i:s', strtotime($expiresAt.' +1 day'));
                }

                $validityTimeId = DB::table('validity_times')->insertGetId([
                    'type' => 'fixed_window',
                    'start_time' => null,
                    'end_time' => null,
                    'fixed_starts_at' => $startsAt,
                    'fixed_expires_at' => $expiresAt,
                    'created_at' => now(),
                    'updated_at' => now(),
                ]);

                DB::table('event_dates')
                    ->where('id', $eventDate->id)
                    ->update(['validity_time_id' => $validityTimeId]);
            });

        Schema::table('event_dates', function (Blueprint $table): void {
            $table->unsignedBigInteger('validity_time_id')->nullable(false)->change();
            $table->foreign('validity_time_id')
                ->references('id')
                ->on('validity_times')
                ->restrictOnDelete();
        });
    }

    public function down(): void
    {
        $validityTimeIds = DB::table('event_dates')
            ->pluck('validity_time_id')
            ->filter()
            ->all();

        Schema::table('event_dates', function (Blueprint $table): void {
            $table->dropForeign(['validity_time_id']);
            $table->dropUnique(['validity_time_id']);
            $table->dropColumn('validity_time_id');
        });

        DB::table('validity_times')->whereIn('id', $validityTimeIds)->delete();
    }
};
