<?php

/**
 * 文件功能：为职务表补充聊天室权限字段
 * 使用 JSON 数组保存可扩展的职务权限码，
 * 并为现有职务按等级回填一份默认权限。
 */

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
{
    /**
     * 执行迁移：新增 permissions 字段并回填默认权限。
     */
    public function up(): void
    {
        Schema::table('positions', function (Blueprint $table) {
            $table->json('permissions')->nullable()->comment('聊天室权限码 JSON 数组');
        });

        $positions = DB::table('positions')->select(['id', 'level'])->get();

        foreach ($positions as $position) {
            DB::table('positions')
                ->where('id', $position->id)
                ->update([
                    'permissions' => json_encode(
                        $this->defaultPermissionsForLevel((int) $position->level),
                        JSON_UNESCAPED_UNICODE
                    ),
                ]);
        }
    }

    /**
     * 回滚迁移：删除 permissions 字段。
     */
    public function down(): void
    {
        Schema::table('positions', function (Blueprint $table) {
            $table->dropColumn('permissions');
        });
    }

    /**
     * 按当前等级回填默认权限。
     *
     * @return list<string>
     */
    private function defaultPermissionsForLevel(int $level): array
    {
        if ($level >= 97) {
            return [
                'room.announcement',
                'room.public_broadcast',
                'room.clear_screen',
                'room.red_packet',
                'room.baccarat_loss_cover',
                'room.fullscreen_effect',
            ];
        }

        if ($level >= 60) {
            return ['room.announcement'];
        }

        return [];
    }
};
