<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

return new class extends Migration
{
    public function up(): void
    {
        $now = Carbon::now();
        $actionIds = DB::table('admin_action_catalog')->pluck('id', 'code');
        $menuIds = DB::table('admin_menus')->pluck('id', 'code');

        $walletMenuId = $menuIds['service.wallet'] ?? null;
        $updateActionId = $actionIds['update'] ?? null;
        if ($walletMenuId !== null && $updateActionId !== null) {
            $exists = DB::table('admin_menu_actions')
                ->where('permission_code', 'service.wallet.adjust')
                ->exists();

            if (! $exists) {
                DB::table('admin_menu_actions')->insert([
                    'menu_id' => $walletMenuId,
                    'action_id' => $updateActionId,
                    'permission_code' => 'service.wallet.adjust',
                    'name' => '钱包补单/冲正',
                    'status' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }

        $oddsMenuId = $menuIds['config.odds'] ?? null;
        $viewActionId = $actionIds['view'] ?? null;
        if ($oddsMenuId !== null && $viewActionId !== null) {
            $exists = DB::table('admin_menu_actions')
                ->where('permission_code', 'config.odds.view')
                ->exists();

            if (! $exists) {
                DB::table('admin_menu_actions')->insert([
                    'menu_id' => $oddsMenuId,
                    'action_id' => $viewActionId,
                    'permission_code' => 'config.odds.view',
                    'name' => '赔率配置查看',
                    'status' => 1,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }
    }

    public function down(): void
    {
        DB::table('admin_menu_actions')
            ->whereIn('permission_code', ['service.wallet.adjust', 'config.odds.view'])
            ->delete();
    }
};
