import Room from "../models/Room.js"
import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'

const nanoid = customAlphabet('1234567890abcdef', 10)

const makeRoom = async (req, res) => {
    console.log(req.body)
    const { roomName, interest, isOpen, moderator } = req.body;
    console.log(roomName, interest, isOpen, moderator)

    const roomId = nanoid()
    const room = await Room.findOne({ roomId })
    while (room) {
        roomId = nanoid()
        room = await Room.findOne({ roomId })
    }

    try {
        if (!isLength(roomName, { min: 3, max: 20 })) {
            return res.status(422).send('채팅방의 이름은 3-20자여야 합니다.')
        } else if (interest == 'Choose...' || interest == '') {
            return res.status(422).send('분야를 반드시 선택하여야 합니다.')
        }
        const newRoom = await new Room({
            roomName,
            interest,
            isOpen,
            moderator,
            roomId,
        }).save()
        console.log(newRoom)
        res.json(newRoom)
    } catch (error) {
        console.log(error)
        res.status(500).send('방생성 에러')
    }
}

const getClosedList = async (req, res) => {
    try {
        let list = await Room.find({ isOpen: false })
        console.log('list가져오기', list)
        return res.json(list)
    } catch (error) {
        res.status(500).send('리스트 불러오기를 실패하였습니다!')
    }
}

export default { makeRoom, getClosedList }
