package com.example.system.chat;

import com.example.system.chat.model.SessionMassage;
import com.example.system.chat.service.SessionService;
import com.example.system.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/session")
public class SessionController {
    @Autowired
    private SessionService sessionService;

    /**
     * 获取所有的会话
     */
    @RequestMapping("/getMessageSession")
    public List<SessionMassage> getMessageSession(HttpServletRequest request) {
        log.info("获取所有的会话");
        //获取登录用户id
        String userToken =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(userToken);
        Integer userId = (Integer) claims.get("userId");
        return sessionService.getMessageSession(userId);
    }

    /**
     * 创建会话
     */
    @RequestMapping("/createSession")
    public Object createSession(@RequestParam List<Integer> friendId, HttpServletRequest request) {
        log.info("创建会话 friend: {}", friendId);
        String userToken =request.getHeader("Authorization");
        Claims claims = JWTUtil.checkToken(userToken);

        Integer userId = (Integer) claims.get("userId");
        friendId.add(userId);
        Object session = sessionService.createSession(friendId);
        log.info("创建会话成功 session: {}", session);
        return session;
    }
}
