import Room from "../models/Room.js"
import Chat from "../models/Chat.js";
import User from "../models/User.js";

const roomEnter = async (req, res) => {
    const roomId = req.body.enterCode
    // console.log(req)

    try {
        const room = await Room.findOne({ roomId })
        if (!room) {
            return res.status(404).send(`참여코드가 존재하지 않습니다.`)
        }

        console.log('roomId존재')

        const name = await Room.findOne({ roomId: roomId }).select('roomName')
        return res.json(name.roomName)

    } catch (error) {
        //알수없는 모든 에러발생시 처리
        console.log(error)
        res.status(500).send('방 참여 에러')
    }
}

const getChatInfo = async (req, res) => {
    const roomId = req.query.roomCode
    try {
        const room_id = await Room.find({ roomId: roomId }).select('_id')  //roomId로 해당 방의 _id를 찾아옴
        let infolist = await Chat.find({ room: room_id }).select('message username createdAt')
        res.json(infolist)
    } catch (error) {
        res.status(500).send('이전 채팅 정보 불러오기를 실패하였습니다!')
    }
}

const getProfileImage = async (req, res) => {
    const nicknamelist = req.query.userlist
    try {
        let imglist = []
        for (let i = 0; i <= nicknamelist.length - 1; i++) {
            const eachimg = await User.find({ nickname: nicknamelist[i] }).select('profileimg')
            imglist = [...imglist, eachimg]
        }
        res.json(imglist)

    } catch (error) {
        res.status(500).send('프로필 사진 정보 불러오기를 실패하였습니다!')
    }
}

export default { roomEnter, getChatInfo, getProfileImage }