import { getSession, getChatList, isExists, sendMessage, formatPhone } from './../whatsapp.js'
import response from './../response.js'

const getList = (req, res) => {
    return response(res, 200, true, '', getChatList(res.locals.sessionId))
}

const send = async (req, res) => {

    // console.log("sessionId")
    // console.log(res.locals.sessionId)

    // console.log("receiver")
    // console.log(req.body)
    // console.log("receiver--------")

    const session = getSession(res.locals.sessionId)
    const receiver = formatPhone(req.body.receiver)
    const delay = req.body.delay
    const { message } = req.body

    try {
        const exists = await isExists(session, receiver)

        if (!exists) {

            const response_code = 400;
            return response(res, response_code, false, 'The receiver number is not exists.')
        }
        
        // console.log("ajin msg ctrl")
        // console.log("session")
        // console.log(session)
        // console.log("receiver")
        // console.log(receiver)
        // console.log("message")
        // console.log(message)
        // console.log("delay")
        // console.log(delay)

        await sendMessage(session, receiver,message, delay)

        response(res, 200, true, 'The message has been successfully sent.')
    } catch (error) {
        response(res, 500, false, 'Failed to send the message..'+error)
    }
}

const sendBulk = async (req, res) => {
    const session = getSession(res.locals.sessionId)
    const errors = []

    for (const [key, data] of req.body.entries()) {
        let { receiver, message, delay } = data

        if (!receiver || !message) {
            errors.push(key)

            continue
        }

        if (!delay || isNaN(delay)) {
            delay = 1000
        }

        receiver = formatPhone(receiver)

        try {
            const exists = await isExists(session, receiver)

            if (!exists) {
                errors.push(key)

                continue
            }

            await sendMessage(session, receiver, message, delay)
        } catch {
            errors.push(key)
        }
    }

    if (errors.length === 0) {
        return response(res, 200, true, 'All messages has been successfully sent.')
    }

    const isAllFailed = errors.length === req.body.length

    response(
        res,
        isAllFailed ? 500 : 200,
        !isAllFailed,
        isAllFailed ? 'Failed to send all messages.' : 'Some messages has been successfully sent.',
        { errors }
    )
}

export { getList, send, sendBulk }
