<?php

declare(strict_types=1);

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('nova_cards', function (Blueprint $table): void {
            $table->unsignedInteger('comments_count')->default(0)->after('remixes_count');
            $table->index('comments_count');
        });

        Schema::table('nova_card_collections', function (Blueprint $table): void {
            $table->boolean('featured')->default(false)->after('official');
            $table->index(['featured', 'updated_at']);
        });

        DB::table('nova_card_challenge_entries')
            ->where('status', 'submitted')
            ->update(['status' => 'active']);

        $driver = Schema::getConnection()->getDriverName();

        if (in_array($driver, ['mysql', 'mariadb'], true)) {
            DB::statement("ALTER TABLE nova_card_challenge_entries MODIFY status ENUM('active','hidden','rejected','featured','winner','submitted') NOT NULL DEFAULT 'active'");
        }
    }

    public function down(): void
    {
        $driver = Schema::getConnection()->getDriverName();

        if (in_array($driver, ['mysql', 'mariadb'], true)) {
            DB::statement("ALTER TABLE nova_card_challenge_entries MODIFY status ENUM('submitted','featured','winner') NOT NULL DEFAULT 'submitted'");
        }

        DB::table('nova_card_challenge_entries')
            ->where('status', 'active')
            ->update(['status' => 'submitted']);

        Schema::table('nova_card_collections', function (Blueprint $table): void {
            $table->dropIndex(['featured', 'updated_at']);
            $table->dropColumn('featured');
        });

        Schema::table('nova_cards', function (Blueprint $table): void {
            $table->dropIndex(['comments_count']);
            $table->dropColumn('comments_count');
        });
    }
};