<?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
    {
        if (! Schema::hasTable('emojis')) {
            return;
        }

        $duplicates = DB::table('emojis')
            ->select('slug', DB::raw('COUNT(*) as aggregate'))
            ->groupBy('slug')
            ->havingRaw('COUNT(*) > 1')
            ->limit(5)
            ->pluck('slug')
            ->all();

        if (! empty($duplicates)) {
            throw new \RuntimeException(
                'Cannot add unique index on emojis.slug because duplicate slugs exist: '.implode(', ', $duplicates)
            );
        }

        Schema::table('emojis', function (Blueprint $table): void {
            $table->unique('slug', 'emojis_slug_unique');
        });
    }

    public function down(): void
    {
        if (! Schema::hasTable('emojis')) {
            return;
        }

        Schema::table('emojis', function (Blueprint $table): void {
            $table->dropUnique('emojis_slug_unique');
        });
    }
};
