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

exports.addborrow = async (req, res) => {
  try {
    const { borrowDate, dueDate, student_FK, book_FK } = req.body;

    const book = await Book.findById(book_FK);
    if (!book) {
      return res.status(404).json({ msg: 'Book not found' });
    }

    const qty = parseInt(book.quantity, 10);
    if (isNaN(qty) || qty <= 0) {
      return res.status(400).json({ msg: 'No copies available to borrow' });
    }

    book.quantity = String(qty - 1);
    await book.save();

    const newborrow = await Borrow.create({
      borrowDate,
      dueDate,
      student_FK,
      book_FK,
      status: 'borrowed',
    });

    res.status(201).json({ msg: 'Borrow recorded', data: newborrow });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to record borrow', error: error.message });
  }
};

exports.getborrow = async (req, res) => {
  try {
    const getborrow = await Borrow.find()
      .populate('student_FK')
      .populate('book_FK');
    res.status(200).json(getborrow);
  } catch (error) {
    res.status(404).json({ msg: 'Borrows not found' });
  }
};

exports.getborrowed = async (req, res) => {
  try {
    const borrowed = await Borrow.find({ status: 'borrowed' })
      .populate('student_FK')
      .populate('book_FK');
    res.status(200).json(borrowed);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to fetch borrowed books' });
  }
};

exports.getreturned = async (req, res) => {
  try {
    const returned = await Borrow.find({ status: 'returned' })
      .populate('student_FK')
      .populate('book_FK');
    res.status(200).json(returned);
  } catch (error) {
    res.status(500).json({ msg: 'Failed to fetch returned books' });
  }
};

exports.returnborrow = async (req, res) => {
  try {
    const borrow = await Borrow.findById(req.params.id).populate('book_FK');

    if (!borrow) {
      return res.status(404).json({ msg: 'Borrow record not found' });
    }

    if (borrow.status === 'returned') {
      return res.status(400).json({ msg: 'Book already returned' });
    }

    borrow.status = 'returned';
    borrow.returnDate = new Date().toISOString().split('T')[0];
    await borrow.save();

    const book = await Book.findById(borrow.book_FK._id);
    if (book) {
      const qty = parseInt(book.quantity, 10) || 0;
      book.quantity = String(qty + 1);
      await book.save();
    }

    res.status(200).json({ msg: 'Book returned successfully', data: borrow });
  } catch (error) {
    res.status(500).json({ msg: 'Failed to return book', error: error.message });
  }
};
