<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('packages', function (Blueprint $table) {
            if (!Schema::hasColumn('packages', 'slug')) {
                $table->string('slug')->default('')->after('name');
            }
            if (!Schema::hasColumn('packages', 'description')) {
                $table->text('description')->nullable()->after('slug');
            }
        });

        // Update existing packages with unique slugs
        if (Schema::hasTable('packages')) {
            $packages = DB::table('packages')->get();
            foreach ($packages as $package) {
                $slug = Str::slug($package->name . '-' . $package->id);
                DB::table('packages')->where('id', $package->id)->update(['slug' => $slug]);
            }
        }

        // Add unique index after updating
        Schema::table('packages', function (Blueprint $table) {
            $table->unique('slug');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('packages', function (Blueprint $table) {
            $table->dropUnique(['slug']);
        });
        Schema::table('packages', function (Blueprint $table) {
            $table->dropColumn(['slug', 'description']);
        });
    }
};