<?php

use App\Models\AdminRole;
use App\Support\AdminPermissionBridge;
use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        if (! Schema::hasTable('admin_role_legacy_permissions')) {
            return;
        }

        $roleIds = DB::table('admin_roles')->pluck('id');

        foreach ($roleIds as $roleId) {
            $legacySlugs = DB::table('admin_role_legacy_permissions')
                ->where('role_id', (int) $roleId)
                ->pluck('permission_slug')
                ->all();

            $slugs = AdminPermissionBridge::normalizeCanonicalLegacySlugs(
                is_array($legacySlugs) ? $legacySlugs : [],
            );

            if ($slugs === []) {
                continue;
            }

            $role = AdminRole::query()->find((int) $roleId);
            if ($role !== null) {
                $role->syncLegacyPermissionSlugs($slugs);
            }
        }

        Schema::dropIfExists('admin_role_legacy_permissions');
    }

    public function down(): void
    {
        // 单向清理：slug 已合并，权限以 admin_role_menu_actions 为准。
    }
};
