<?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
    {
        // 1) 유니크 인덱스 존재 시 제거 (information_schema로 확인)
        $hasUnique = DB::table('information_schema.statistics')
            ->whereRaw('TABLE_SCHEMA = DATABASE()')
            ->where('TABLE_NAME', 'menus')
            ->where('INDEX_NAME', 'menus_tenant_slug_unique')
            ->exists();

        if ($hasUnique) {
            Schema::table('menus', function (Blueprint $table) {
                $table->dropUnique('menus_tenant_slug_unique');
            });
        }

        // 2) slug 컬럼 존재 시 제거
        if (Schema::hasColumn('menus', 'slug')) {
            Schema::table('menus', function (Blueprint $table) {
                $table->dropColumn('slug');
            });
        }
    }

    public function down(): void
    {
        // 1) slug 컬럼 복구
        if (! Schema::hasColumn('menus', 'slug')) {
            Schema::table('menus', function (Blueprint $table) {
                $table->string('slug', 150)->nullable()->comment('메뉴 슬러그(권한 키)');
            });
        }

        // 2) 유니크 인덱스 복구 (없을 때만)
        $hasUnique = DB::table('information_schema.statistics')
            ->whereRaw('TABLE_SCHEMA = DATABASE()')
            ->where('TABLE_NAME', 'menus')
            ->where('INDEX_NAME', 'menus_tenant_slug_unique')
            ->exists();

        if (! $hasUnique) {
            Schema::table('menus', function (Blueprint $table) {
                $table->unique(['tenant_id', 'slug'], 'menus_tenant_slug_unique');
            });
        }
    }
};
