const express = require('express');
const { Wishlist, Book, User } = require('../models');
const { authenticateToken } = require('../middleware/auth');
const router = express.Router();

// Get User's Wishlist
router.get('/', authenticateToken, async (req, res) => {
    try {
        const wishlist = await Wishlist.findAll({
            where: { user_id: req.user.id },
            include: [{
                model: Book,
                attributes: ['id', 'title', 'price', 'originalPrice', 'image', 'author', 'rating', 'stock']
            }],
            order: [['created_at', 'DESC']]
        });
        res.json(wishlist);
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Add to Wishlist
router.post('/', authenticateToken, async (req, res) => {
    try {
        const { bookId } = req.body;
        const exists = await Wishlist.findOne({
            where: {
                user_id: req.user.id,
                book_id: bookId
            }
        });

        if (exists) {
            return res.status(400).json({ message: 'Book already in wishlist' });
        }

        const item = await Wishlist.create({
            user_id: req.user.id,
            book_id: bookId
        });

        res.status(201).json(item);
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Remove from Wishlist
router.delete('/:bookId', authenticateToken, async (req, res) => {
    try {
        const { bookId } = req.params;
        const deleted = await Wishlist.destroy({
            where: {
                user_id: req.user.id,
                book_id: bookId
            }
        });

        if (!deleted) {
            return res.status(404).json({ message: 'Item not found in wishlist' });
        }

        res.json({ message: 'Removed from wishlist' });
    } catch (error) {
        res.status(500).json({ message: 'Server error', error: error.message });
    }
});

// Check if book is in wishlist
router.get('/check/:bookId', authenticateToken, async (req, res) => {
    try {
        const item = await Wishlist.findOne({
            where: {
                user_id: req.user.id,
                book_id: req.params.bookId
            }
        });
        res.json({ inWishlist: !!item });
    } catch (error) {
        res.status(500).json({ message: 'Server error' });
    }
});

module.exports = router;
