// import { useState } from 'react'
import Chat from "../models/Chat.js"
import { customAlphabet } from 'nanoid'
import isLength from 'validator/lib/isLength.js'

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

const makeChat = async (req, res) => {
    const { name, interest, isOpen } = req.body;

    const roomId = nanoid()
    const chat = await Chat.findOne({ roomId })
    while (chat) {
        roomId = nanoid()
        chat = await Chat.findOne({ roomId })
    }

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

const hello = (req, res) => {
    res.send('Hello from users controller')
}

export default { makeChat, hello }