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


exports.getbook = async (req, res) => {
  try {
    const books = await Book.find();
    if (!books) {
      return res.status(404).json({ message: 'Books not found' });
    }
    res.json(books);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.getbookbyid = async (req, res) => {
  try {
    const bookById = await Book.findById(req.params.id);
    if (!bookById) {
      return res.status(404).json({ message: 'Book not found' });
    }
    res.json(bookById);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
};

exports.addbook = async (req, res) => {
  try {
    const { title, author, quantity } = req.body
    const newbook = await Book.create({
      title,
      author,
      quantity,
    });

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

exports.updatebook = async (req, res) => {
  try {
    const updatebooks = await Book.findByIdAndUpdate(
      req.params.id,
      req.body,
      { new: true }
    );
    if (!updatebooks) return res.status(404).json({ msg: " book not found" })

    res.json({ msg: "Book updated successfully", data: updatebooks });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}

exports.deletebook = async (req, res) => {
  try {
    const deletebook = await Book.findByIdAndDelete(
      req.params.id
    );
    if (!deletebook) {
      return res.status(404).json({ message: 'Book not found' });
    }
    res.json({ message: 'Book deleted successfully' });
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
}
