const express = require('express');
const pool = require('../config/db');
const auth = require('../middleware/auth');

const router = express.Router();
router.use(auth);

router.get('/', async (req, res) => {
  try {
    const { search, category } = req.query;
    let sql = 'SELECT * FROM books WHERE 1=1';
    const params = [];

    if (search) {
      sql += ' AND (title LIKE ? OR author LIKE ? OR isbn LIKE ?)';
      const term = `%${search}%`;
      params.push(term, term, term);
    }
    if (category) {
      sql += ' AND category = ?';
      params.push(category);
    }
    sql += ' ORDER BY title ASC';

    const [books] = await pool.query(sql, params);
    res.json(books);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch books.' });
  }
});

router.get('/:id', async (req, res) => {
  try {
    const [books] = await pool.query('SELECT * FROM books WHERE id = ?', [req.params.id]);
    if (books.length === 0) return res.status(404).json({ message: 'Book not found.' });
    res.json(books[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to fetch book.' });
  }
});

router.post('/', async (req, res) => {
  try {
    const { title, author, isbn, category, quantity, published_year } = req.body;
    if (!title || !author) {
      return res.status(400).json({ message: 'Title and author are required.' });
    }
    const qty = quantity || 1;
    const [result] = await pool.query(
      'INSERT INTO books (title, author, isbn, category, quantity, available, published_year) VALUES (?, ?, ?, ?, ?, ?, ?)',
      [title, author, isbn || null, category || null, qty, qty, published_year || null]
    );
    const [books] = await pool.query('SELECT * FROM books WHERE id = ?', [result.insertId]);
    res.status(201).json(books[0]);
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ message: 'ISBN already exists.' });
    }
    console.error(err);
    res.status(500).json({ message: 'Failed to create book.' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { title, author, isbn, category, quantity, published_year } = req.body;
    const [existing] = await pool.query('SELECT * FROM books WHERE id = ?', [req.params.id]);
    if (existing.length === 0) return res.status(404).json({ message: 'Book not found.' });

    const book = existing[0];
    const borrowed = book.quantity - book.available;
    const newQty = quantity !== undefined ? quantity : book.quantity;
    if (newQty < borrowed) {
      return res.status(400).json({ message: `Quantity cannot be less than borrowed copies (${borrowed}).` });
    }
    const newAvailable = newQty - borrowed;

    await pool.query(
      'UPDATE books SET title=?, author=?, isbn=?, category=?, quantity=?, available=?, published_year=? WHERE id=?',
      [
        title || book.title,
        author || book.author,
        isbn !== undefined ? isbn : book.isbn,
        category !== undefined ? category : book.category,
        newQty,
        newAvailable,
        published_year !== undefined ? published_year : book.published_year,
        req.params.id,
      ]
    );
    const [books] = await pool.query('SELECT * FROM books WHERE id = ?', [req.params.id]);
    res.json(books[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to update book.' });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const [active] = await pool.query(
      "SELECT id FROM borrowings WHERE book_id = ? AND status = 'borrowed'",
      [req.params.id]
    );
    if (active.length > 0) {
      return res.status(400).json({ message: 'Cannot delete book with active borrowings.' });
    }
    const [result] = await pool.query('DELETE FROM books WHERE id = ?', [req.params.id]);
    if (result.affectedRows === 0) return res.status(404).json({ message: 'Book not found.' });
    res.json({ message: 'Book deleted successfully.' });
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to delete book.' });
  }
});

module.exports = router;
