const itemService = require("../service/item.service");

module.exports = {
    listItems,
    filterItems,
    addItem,
    updateItemPrice,
    getItemByName,
    deleteItem,
    getImages,
    searchItems,
    getCategories
};

function listItems(req, res) {
    itemService.filterItemsByCategory("book").then(items => {
        res.json({items: items});
    }).catch(err => {
        res.status(400).json({message: err});
    });
}

function filterItems(req, res) {
    const category = req.query.category;
    itemService.filterItemsByCategory(category).then(items => {
        res.json({items: items});
    }).catch(err => {
        res.status(400).json({message: err});
    });
}

function addItem(req, res, next) {
    const images = req.files
    itemService.addItem(images, req.body.product_name, req.body.description, req.body.price, req.body.category, req.body.userID).then(() => {
        res.json({message: "Item added successfully"});
    }).catch(err => {
        res.status(400).json({message: err});
    });


}

function updateItemPrice(req, res) {
    const {item_id, new_price} = req.body;
    itemService.updateItemPrice(item_id, new_price).then(() => {
        res.json({message: "Item price updated successfully"});
    }).catch(err => {
        res.status(400).json({message: err});
    });
}

function getItemByName(req, res) {
    const item_name = req.params.name;
    itemService.getItemByName(item_name).then(item => {
        res.json(item);
    }).catch(err => {
        res.status(400).json({message: err});
    });
}

function deleteItem(req, res) {
    const item_id = req.params.id;
    itemService.deleteItem(item_id).then(() => {
        res.json({message: "Item deleted successfully"});
    }).catch(err => {
        res.status(400).json({message: err});
    });
}

function getImages(req, res){
    const itemID = req.params.id
    if(isNaN(itemID)){
        res.status(404).json({})
        return
    }
    itemService.getImages(itemID).then(urls => res.status(200).json(urls))
        .catch(err =>{
            res.status(400).json({message: err})
        })
}

function  getCategories(req, res){
    itemService.getCategories().then(cats => res.status(200).json(cats))
        .catch(err =>{
            res.status(400).json({message: err})
        })
}

async function searchItems(req, res) {
    try {
        const keyword = req.query.keyword; // assuming the search term is passed as a query parameter
        const items = await itemService.searchItems(keyword);
        res.json(items);
    } catch (error) {
        res.status(500).send(error.message);
    }
}