<?php

namespace App\Console\Commands;

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

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()
    {


        $payload = null;
        $statusCode = null;
        $body = null;

        try {
            $client = new Client([
                'timeout' => 10,
                'connect_timeout' => 10,
            ]);
            $res = $client->request('GET', 'https://api1.usvip.org/api/stock_mode/check_negative');
            $statusCode = $res->getStatusCode();
            $body = (string) $res->getBody();
            $payload = json_decode($body, true);
        } catch (\Throwable $e) {
            $this->error('Failed to request stock_mode API: ' . $e->getMessage());
            Log::error('stock_mode/check_negative API request failed', [
                'error' => $e->getMessage(),
            ]);
        }

        if ($statusCode && $statusCode >= 200 && $statusCode < 300 && is_array($payload)) {
            Log::info('stock_mode/check_negative API json result', [
                'status' => $statusCode,
                'payload' => $payload,
            ]);
            $apiNegativeRooms = [];

            if (isset($payload['data']) && is_array($payload['data'])) {
                foreach ($payload['data'] as $level => $room) {
                    if (!is_array($room)) {
                        continue;
                    }

                    $isNegative = $room['is_negative'] ?? false;
                    if ($isNegative) {
                        $apiNegativeRooms[] = [
                            'level' => $level,
                            'sort_id' => $room['sort_id'] ?? null,
                            'stock' => $room['stock'] ?? null,
                            'stock_raw' => $room['stock_raw'] ?? null,
                            'level_base' => $room['level_base'] ?? null,
                            'level_base_raw' => $room['level_base_raw'] ?? null,
                        ];
                    }
                }
            }

            if (!empty($apiNegativeRooms)) {
                $apiLines = [];
                $apiLines[] = '【库存模式报警】PigRoomStockStatic2库存为负';
                $apiLines[] = '时间: ' . date('Y-m-d H:i:s');
                foreach ($apiNegativeRooms as $info) {
                    $apiLines[] = sprintf(
                        '房间 Level=%s, SortID=%s, Stock=%s (原始=%s), LevelBase=%s (原始=%s)',
                        $info['level'],
                        $info['sort_id'] ?? '-',
                        $info['stock'] ?? '-',
                        $info['stock_raw'] ?? '-',
                        $info['level_base'] ?? '-',
                        $info['level_base_raw'] ?? '-'
                    );
                }

                try {
                    TelegramBot::getDefault()->sendMsg(implode("\n", $apiLines));
                } catch (\Throwable $e) {
                    Log::error('Failed to send Telegram alert (API): ' . $e->getMessage());
                }
            }
        } elseif ($statusCode) {
            // HTTP 层面返回了非 2xx 或 JSON 解析失败；也把响应体打到日志里，方便排查
            Log::warning('stock_mode/check_negative API non-ok response', [
                'status' => $statusCode,
                'body' => $body,
                'json_decode_error' => json_last_error_msg(),
            ]);
        }

        // 低/中/高三个房间：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;
    }
}

