<?php

declare(strict_types=1);

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        $afterColumn = Schema::hasColumn('worlds', 'recap_intro')
            ? 'recap_intro'
            : (Schema::hasColumn('worlds', 'published_at') ? 'published_at' : null);
        $hasRecapEditorNote = Schema::hasColumn('worlds', 'recap_editor_note');
        $hasRecapCoverPath = Schema::hasColumn('worlds', 'recap_cover_path');

        Schema::table('worlds', function (Blueprint $table) use ($afterColumn, $hasRecapEditorNote, $hasRecapCoverPath): void {
            if (! $hasRecapEditorNote) {
                $column = $table->text('recap_editor_note')->nullable();

                if ($afterColumn !== null) {
                    $column->after($afterColumn);
                }
            }

            if (! $hasRecapCoverPath) {
                $column = $table->string('recap_cover_path', 2048)->nullable();

                if (! $hasRecapEditorNote) {
                    $column->after('recap_editor_note');
                } elseif ($afterColumn !== null) {
                    $column->after($afterColumn);
                }
            }
        });
    }

    public function down(): void
    {
        Schema::table('worlds', function (Blueprint $table): void {
            $columns = array_values(array_filter([
                Schema::hasColumn('worlds', 'recap_editor_note') ? 'recap_editor_note' : null,
                Schema::hasColumn('worlds', 'recap_cover_path') ? 'recap_cover_path' : null,
            ]));

            if ($columns !== []) {
                $table->dropColumn($columns);
            }
        });
    }
};