

const router = require('express-promise-router')();

const storageprofile = require('../../multer');
const UserImage = require('../../models/userimage');


router.post('/upload/user/:userId', storageprofile.single('images'), async (req, res) => {
    //  console.log(req.body.shopId);
    const images = req.file;
    const user_id = req.body.userId

    // console.log(req);

        await UserImage.create({
            user_id: req.params.userId,
            image: images.buffer,
            type: images.mimetype
         });
        res.send('success')
})
//get file
router.get('/file/user/:userId', async (req, res) => {
    const existingImage = await UserImage.findOne({
        where: {
            user_id: req.params.userId
        }
    })
    if (existingImage){
        const urlimg = existingImage.image.toString('base64');
        const dataimg = {
            url: urlimg,
            type: existingImage.type
        }
        res.status(200).send(dataimg);
    }else{   
        res.status(200).send();
    }
   
    
})
router.put('/file/user/:userId',  storageprofile.single('images') ,async (req, res) => {
    const editImage = req.file;
    const profileimage = {
        image: editImage.buffer
    }

    const userId = req.params.userId;

    await UserImage.update(
        profileimage,
        { where: {user_id: userId } }
      )
      res.send('success')
})

module.exports = router;