const Item = require('../models/Item');

exports.getItems = async (req, res) => {
  try {
    const items = await Item.find({ user: req.user._id }).sort({ createdAt: -1 });
    res.json({ items });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.getItem = async (req, res) => {
  try {
    const item = await Item.findOne({ _id: req.params.id, user: req.user._id });
    if (!item) {
      return res.status(404).json({ message: 'Item not found' });
    }
    res.json({ item });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.createItem = async (req, res) => {
  try {
    const { title, description } = req.body;

    if (!title) {
      return res.status(400).json({ message: 'Title is required' });
    }

    const item = await Item.create({
      title,
      description: description || '',
      user: req.user._id,
    });

    res.status(201).json({ item });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.updateItem = async (req, res) => {
  try {
    const { title, description } = req.body;

    const item = await Item.findOne({ _id: req.params.id, user: req.user._id });
    if (!item) {
      return res.status(404).json({ message: 'Item not found' });
    }

    if (title !== undefined) item.title = title;
    if (description !== undefined) item.description = description;

    await item.save();

    res.json({ item });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.deleteItem = async (req, res) => {
  try {
    const item = await Item.findOneAndDelete({ _id: req.params.id, user: req.user._id });
    if (!item) {
      return res.status(404).json({ message: 'Item not found' });
    }
    res.json({ message: 'Item deleted' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}
