<?php

namespace App\Support;

use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

/** 确保期号「重开」独立 permission_code 存在，避免与「管理」共用 publish 导致勾选无法拆分。 */
final class AdminDrawPermissionMenuActionSync
{
    public static function syncMissing(): int
    {
        if (DB::table('admin_menu_actions')->where('permission_code', 'draw.reopen.manage')->exists()) {
            return 0;
        }

        $menuId = (int) DB::table('admin_menus')->where('code', 'draw.results')->value('id');
        $actionId = DB::table('admin_action_catalog')->where('code', 'manage')->value('id');
        if ($menuId === 0 || $actionId === null) {
            return 0;
        }

        $now = Carbon::now();
        DB::table('admin_menu_actions')->insert([
            'menu_id' => $menuId,
            'action_id' => (int) $actionId,
            'permission_code' => 'draw.reopen.manage',
            'name' => '期号重开',
            'status' => 1,
            'created_at' => $now,
            'updated_at' => $now,
        ]);

        return 1;
    }
}
