<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('galleries', function (Blueprint $table) {
            if (! Schema::hasColumn('galleries', 'images_path')) {
                return;
            }

            $duplicates = DB::table('galleries')
                ->select('images_path', DB::raw('COUNT(*) as aggregate'))
                ->whereNotNull('images_path')
                ->groupBy('images_path')
                ->having('aggregate', '>', 1)
                ->pluck('images_path')
                ->all();

            if (! empty($duplicates)) {
                foreach ($duplicates as $path) {
                    $idsToKeep = DB::table('galleries')
                        ->where('images_path', $path)
                        ->orderBy('id')
                        ->limit(1)
                        ->pluck('id');

                    DB::table('galleries')
                        ->where('images_path', $path)
                        ->whereNotIn('id', $idsToKeep)
                        ->delete();
                }
            }

            $table->unique('images_path');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('galleries', function (Blueprint $table) {
            if (! Schema::hasColumn('galleries', 'images_path')) {
                return;
            }

            $table->dropUnique('galleries_images_path_unique');
        });
    }
};
