const express = require("express");
const router = express.Router();
const itemController = require("../controller/item.controller");
const multer = require('multer')
const crypto = require('crypto')
const path = require("path")

const storage = multer.diskStorage({
    destination: function(req, file, cb){
        cb(null, "./uploads/")
    },
    filename: function(req, file, cb){
        crypto.randomBytes(16, (err, buf) =>{
            if (err){
                return cb(err)
            }
            let filename = buf.toString("hex")+path.extname(file.originalname)
            cb(null, filename)
        })
    }
})


const upload = multer({storage: storage})


// get to /item to get a list of all items
router.get("/", itemController.listItems);

// post to /item/filter?category=XXXX to get item in a category
router.get("/filter", itemController.filterItems);

// post to /item/add with json {title, description, price, category, picture_url, seller_id}
router.post("/add",upload.array("images", 10), itemController.addItem);

router.post("/updatePrice", itemController.updateItemPrice);
router.get("/name/:name", itemController.getItemByName);
router.delete("/delete/:id", itemController.deleteItem);

router.get("/images/:id", itemController.getImages)
router.get('/search', itemController.searchItems);

router.get("/categories", itemController.getCategories)

module.exports = router;
