<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasColumn('news', 'slug')) {
            Schema::table('news', function (Blueprint $table) {
                $table->string('slug')->nullable()->after('title');
            });
        }

        try {
            Schema::table('news', function (Blueprint $table) {
                $table->unique('slug', 'news_slug_unique');
            });
        } catch (\Exception $e) {
            // Index already exists, ignore
        }

        foreach (DB::table('news')->get() as $newsItem) {
            $baseSlug = Str::slug($newsItem->title);
            $slug = $baseSlug;
            $counter = 1;

            while (DB::table('news')->where('slug', $slug)->exists()) {
                $slug = $baseSlug.'-'.$counter;
                $counter++;
            }

            DB::table('news')->where('id', $newsItem->id)->update(['slug' => $slug]);
        }

        try {
            Schema::table('news', function (Blueprint $table) {
                $table->string('slug')->unique()->nullable(false)->change();
            });
        } catch (\Exception $e) {
            // Already has unique constraint, ignore
        }
    }

    public function down(): void
    {
        Schema::table('news', function (Blueprint $table) {
            $table->dropColumn('slug');
        });
    }
};
