const bcrypt = require('bcrypt')
const User = require('../../models/user/userData')
const getPageData = require('../../models/common/getPageData')

module.exports = {
    get: async (req, res, next) => {
        try {
            let { currentPage, limit } = req.query
            if (!currentPage || !limit) return res.status(401).json({ message: 'No Query!' })
            //設置資料偏移量
            const skip = (currentPage - 1) * parseInt(limit)
            //當前頁面資訊
            const pageInfo = { skip, limit, order: 'ASC', searchQueries: null, table: 'user' }
            //取得頁面資料
            const { totalPages, pageData } = await getPageData(pageInfo)
            res.status(200).json({ totalPages: totalPages, pageData: pageData })
        } catch (err) {
            res.status(500).json(err)
        }
    },
    post: async (req, res, next) => {
        try {
            let { name, username, password } = req.body
            if (!name || !username || !password) return res.status(401).json({ message: '缺少必要欄位' })
            const hashedPassword = await bcrypt.hash(password, 10)
            const userInfo = { name: name, username: username, password: hashedPassword }
            await User.post(userInfo)
            req.logOut()
            res.redirect('./../login')
        } catch (err) {
            res.status(500).json(err)
        }
    },
    delete: async (req, res, next) => {
        try {
            const { userid } = req.params
            if (!userid) return res.status(401).json({ messgae: 'No Params!' })
            await User.delete(userid)
            res.status(200).json({ message: '刪除成功' })
        } catch (err) {
            res.status(500).json(err)
        }
    },
    update: async (req, res, next) => {
        try {
            const { userid } = req.params
            const { password } = req.body
            const hashedPassword = await bcrypt.hash(password, 10)
            if (!userid) return res.status(401).json({ messgae: 'No Params!' })
            await User.update(userid, hashedPassword)
            res.status(200).json({ message: '修改成功' })
        } catch (err) {
            res.status(500).json(err)
        }
    },
}
