<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('artworks', function (Blueprint $table): void {
            if (! Schema::hasColumn('artworks', 'has_missing_thumbnails')) {
                $table->boolean('has_missing_thumbnails')
                    ->default(false)
                    ->after('thumb_ext');
            }

            if (! Schema::hasColumn('artworks', 'missing_thumbnail_variants_json')) {
                $table->json('missing_thumbnail_variants_json')
                    ->nullable()
                    ->after('has_missing_thumbnails');
            }

            if (! Schema::hasColumn('artworks', 'thumbnails_checked_at')) {
                $table->timestamp('thumbnails_checked_at')
                    ->nullable()
                    ->after('missing_thumbnail_variants_json');
            }
        });

        Schema::table('artworks', function (Blueprint $table): void {
            if (Schema::hasColumn('artworks', 'has_missing_thumbnails')) {
                $table->index('has_missing_thumbnails', 'artworks_missing_thumbnails_idx');
            }

            if (Schema::hasColumn('artworks', 'thumbnails_checked_at')) {
                $table->index('thumbnails_checked_at', 'artworks_thumbnails_checked_idx');
            }
        });
    }

    public function down(): void
    {
        Schema::table('artworks', function (Blueprint $table): void {
            try {
                $table->dropIndex('artworks_missing_thumbnails_idx');
            } catch (Throwable) {
            }

            try {
                $table->dropIndex('artworks_thumbnails_checked_idx');
            } catch (Throwable) {
            }

            $columns = [];

            foreach (['has_missing_thumbnails', 'missing_thumbnail_variants_json', 'thumbnails_checked_at'] as $column) {
                if (Schema::hasColumn('artworks', $column)) {
                    $columns[] = $column;
                }
            }

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