<?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
    {
        Schema::table('featured_groups', function (Blueprint $table): void {
            $table->string('code')->nullable()->after('tenant_code');
        });

        $usedCodes = [];

        DB::table('featured_groups')
            ->select(['id', 'tenant_code', 'group_name'])
            ->orderBy('id')
            ->get()
            ->each(function (object $group) use (&$usedCodes): void {
                $baseCode = Str::slug($group->group_name) ?: "group-{$group->id}";
                $code = $baseCode;
                $suffix = 2;

                while (isset($usedCodes[$group->tenant_code][$code])) {
                    $code = "{$baseCode}-{$suffix}";
                    $suffix++;
                }

                $usedCodes[$group->tenant_code][$code] = true;

                DB::table('featured_groups')
                    ->where('id', $group->id)
                    ->update(['code' => $code]);
            });

        Schema::table('featured_groups', function (Blueprint $table): void {
            $table->string('code')->nullable(false)->change();
            $table->unique(['tenant_code', 'code']);
        });
    }

    public function down(): void
    {
        Schema::table('featured_groups', function (Blueprint $table): void {
            $table->dropUnique(['tenant_code', 'code']);
            $table->dropColumn('code');
        });
    }
};
