<?php

namespace App\Console\Commands;

use App\Notification\TelegramBot;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;

class CheckStockModeNegative extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'stock_mode:check_negative';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Check stock-mode rooms (low/mid/high) and send Telegram alert when Stock is negative';

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        // 低/中/高三个房间：SortID 1,2,3
        $rooms = DB::connection('write')
            ->table('QPPlatformDB.dbo.RoomStockStatic2')
            ->where('GameID', 0)
            ->whereIn('SortID', [1, 2, 3])
            ->get();

        if ($rooms->isEmpty()) {
            return 0;
        }

        $negativeRooms = [];
        foreach ($rooms as $room) {
            if ($room->Stock < 0) {
                // 数据库存储的是 *100 后的值，这里除以 100 便于阅读
                $negativeRooms[] = [
                    'sort_id' => $room->SortID,
                    'stock_raw' => $room->Stock,
                    'stock' => round($room->Stock / 100, 2),
                    'level_base' => isset($room->LevelBase) ? round($room->LevelBase / 100, 2) : null,
                ];
            }
        }

        if (empty($negativeRooms)) {
            return 0;
        }

        $lines = [];
        $lines[] = '【库存模式报警】RoomStockStatic2 库存为负';
        $lines[] = '时间: ' . date('Y-m-d H:i:s');
        foreach ($negativeRooms as $info) {
            $lines[] = sprintf(
                '房间 SortID=%d, Stock=%s (原始=%d), LevelBase=%s',
                $info['sort_id'],
                $info['stock'],
                $info['stock_raw'],
                $info['level_base'] === null ? '-' : $info['level_base']
            );
        }

        try {
            TelegramBot::getDefault()->sendMsgWithEnv(implode("\n", $lines));
        } catch (\Throwable $e) {
            $this->error('Failed to send Telegram alert: ' . $e->getMessage());
        }

        return 0;
    }
}

