const query = require('../db/db-query')

module.exports = {
    get: async (id, username) => {
        try {
            let sql = ''
            id ? (sql = `select * from user where USER_ID ='${id}' `) : (sql = `select * from user where USER_USERNAME ='${username}' `)
            let user = await query(sql)
            //set user format
            user = user[0]
            for (let key in user) {
                const newKey = key.split('_').pop().toLocaleLowerCase()
                delete Object.assign(user, { [newKey]: user[key] })[key]
            }
            return user
        } catch (err) {
            return err
        }
    },
    post: async user => {
        try {
            let sql = `insert into user(USER_USERNAME,USER_PASSWORD,USER_NAME) values ('${user.username}','${user.password}','${user.name}')`
            await query(sql)
            return
        } catch (err) {
            return err
        }
    },
    delete: async id => {
        let sql = `DELETE FROM user WHERE USER_ID = '${id}'`
        try {
            await query(sql)
            return
        } catch (err) {
            return err
        }
    },
    update: async (id, password) => {
        let sql = `UPDATE user SET USER_PASSWORD = '${password}' WHERE USER_ID = '${id}'`
        try {
            await query(sql)
            return
        } catch (err) {
            return err
        }
    },
}
