const db = require('../config/db');

// Get all wishlists with product and user details
const getAllWishlists = async (req, res) => {
  try {
    const [rows] = await db.query(`
      SELECT 
        w.id,
        i.name as product_name,
        w.quantity,
        u.name as wish_by_name,
        u.id as wish_by_id,
        w.created_at
      FROM wishlists w
      LEFT JOIN items i ON w.item_id = i.id
      LEFT JOIN users u ON w.user_id = u.id
      WHERE w.status = 1
      ORDER BY w.created_at DESC
    `);
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching wishlists:', error);
    res.status(500).json({ success: false, msg: 'Error fetching wishlists' });
  }
};

// Get wishlist by ID
const getWishlistById = async (req, res) => {
  try {
    const { id } = req.params;
    const [rows] = await db.query(`
      SELECT 
        w.*,
        i.name as product_name,
        u.name as user_name,
        u.id as user_id
      FROM wishlists w
      LEFT JOIN items i ON w.item_id = i.id
      LEFT JOIN users u ON w.user_id = u.id
      WHERE w.id = ?
    `, [id]);
    
    if (rows.length === 0) {
      return res.status(404).json({ success: false, msg: 'Wishlist not found' });
    }
    
    res.json({ success: true, data: rows[0] });
  } catch (error) {
    console.error('Error fetching wishlist:', error);
    res.status(500).json({ success: false, msg: 'Error fetching wishlist' });
  }
};

// Get users who wishlisted a specific product
const getProductWishlistUsers = async (req, res) => {
  try {
    const { item_id } = req.params;
    const [rows] = await db.query(`
      SELECT 
        u.id,
        u.name,
        u.email,
        w.quantity,
        w.created_at as wishlisted_at
      FROM wishlists w
      LEFT JOIN users u ON w.user_id = u.id
      WHERE w.item_id = ? AND w.status = 1
      ORDER BY w.created_at DESC
    `, [item_id]);
    
    res.json({ success: true, data: rows });
  } catch (error) {
    console.error('Error fetching product wishlist users:', error);
    res.status(500).json({ success: false, msg: 'Error fetching product wishlist users' });
  }
};

// Create new wishlist
const createWishlist = async (req, res) => {
  try {
    const { user_id, item_id, quantity } = req.body;
    
    if (!user_id || !item_id) {
      return res.status(400).json({ success: false, msg: 'User ID and Item ID are required' });
    }
    
    const [result] = await db.query(
      'INSERT INTO wishlists (user_id, item_id, quantity) VALUES (?, ?, ?)',
      [user_id, item_id, quantity || 1]
    );
    
    const [newWishlist] = await db.query('SELECT * FROM wishlists WHERE id = ?', [result.insertId]);
    
    res.status(201).json({ success: true, data: newWishlist[0], msg: 'Wishlist created successfully' });
  } catch (error) {
    console.error('Error creating wishlist:', error);
    res.status(500).json({ success: false, msg: 'Error creating wishlist' });
  }
};

// Update wishlist
const updateWishlist = async (req, res) => {
  try {
    const { id } = req.params;
    const { quantity } = req.body;
    
    const [result] = await db.query(
      'UPDATE wishlists SET quantity = ?, updated_at = NOW() WHERE id = ?',
      [quantity, id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, msg: 'Wishlist not found' });
    }
    
    const [updatedWishlist] = await db.query('SELECT * FROM wishlists WHERE id = ?', [id]);
    
    res.json({ success: true, data: updatedWishlist[0], msg: 'Wishlist updated successfully' });
  } catch (error) {
    console.error('Error updating wishlist:', error);
    res.status(500).json({ success: false, msg: 'Error updating wishlist' });
  }
};

// Delete wishlist (soft delete)
const deleteWishlist = async (req, res) => {
  try {
    const { id } = req.params;
    
    const [result] = await db.query(
      'UPDATE wishlists SET status = 0, updated_at = NOW() WHERE id = ?',
      [id]
    );
    
    if (result.affectedRows === 0) {
      return res.status(404).json({ success: false, msg: 'Wishlist not found' });
    }
    
    res.json({ success: true, msg: 'Wishlist deleted successfully' });
  } catch (error) {
    console.error('Error deleting wishlist:', error);
    res.status(500).json({ success: false, msg: 'Error deleting wishlist' });
  }
};

module.exports = {
  getAllWishlists,
  getWishlistById,
  getProductWishlistUsers,
  createWishlist,
  updateWishlist,
  deleteWishlist
};
