<?php

/**
 * 文件功能：将旧的冻结权限合并到封号权限
 * 确保已配置 room.user_freeze 的职务在合并后自动继承 room.user_ban。
 */

use App\Models\Position;
use Illuminate\Database\Migrations\Migration;

return new class extends Migration
{
    /**
     * 方法功能：把冻结权限迁移为封号权限。
     */
    public function up(): void
    {
        Position::query()->each(function (Position $position): void {
            $permissions = array_values($position->permissions ?? []);

            if (! in_array('room.user_freeze', $permissions, true)) {
                return;
            }

            $normalizedPermissions = array_values(array_unique(array_map(
                fn (string $permission): string => $permission === 'room.user_freeze' ? 'room.user_ban' : $permission,
                $permissions,
            )));

            $position->forceFill([
                'permissions' => $normalizedPermissions,
            ])->save();
        });
    }

    /**
     * 方法功能：回滚时把合并后的封号权限恢复为冻结权限。
     */
    public function down(): void
    {
        Position::query()->each(function (Position $position): void {
            $permissions = array_values($position->permissions ?? []);

            if (! in_array('room.user_ban', $permissions, true)) {
                return;
            }

            $normalizedPermissions = array_values(array_unique(array_map(
                fn (string $permission): string => $permission === 'room.user_ban' ? 'room.user_freeze' : $permission,
                $permissions,
            )));

            $position->forceFill([
                'permissions' => $normalizedPermissions,
            ])->save();
        });
    }
};
