<?php

namespace app\listener\chat;

use app\services\chat\SessionService;
use think\swoole\WebSocket;
use think\facade\Cache;

/**
 * 会话结束监听器
 */
class ChatSessionEnd
{
    private $sessionService;

    public function __construct()
    {
        $this->sessionService = new SessionService();
    }

    public function handle(array $event, WebSocket $ws)
    {
        $sessionId = $event['sessionId'] ?? 0;

        if (!$sessionId) {
            $ws->emit('chat_error', ['error' => 'session_id_required']);
            return;
        }

        // 获取操作者ID（从fd映射表获取）
        $fd = $ws->getSender();
        $tableFd = app('swoole.table.fd');
        $fdInfo = $tableFd->get((string)$fd);
        $operatorId = $fdInfo['user_id'] ?? 0;

        $result = $this->sessionService->endSession($sessionId, $operatorId);

        if ($result) {
            $ws->emit('chat_session_ended', [
                'success' => true,
                'sessionId' => $sessionId
            ]);
        } else {
            $ws->emit('chat_error', ['error' => 'end_session_failed']);
        }
    }
}
