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, status } = req.query;
    let sql = 'SELECT * FROM members WHERE 1=1';
    const params = [];

    if (search) {
      sql += ' AND (name LIKE ? OR email LIKE ? OR phone LIKE ?)';
      const term = `%${search}%`;
      params.push(term, term, term);
    }
    if (status) {
      sql += ' AND status = ?';
      params.push(status);
    }
    sql += ' ORDER BY name ASC';

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

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

router.post('/', async (req, res) => {
  try {
    const { name, email, phone, address, status } = req.body;
    if (!name || !email) {
      return res.status(400).json({ message: 'Name and email are required.' });
    }
    const [result] = await pool.query(
      'INSERT INTO members (name, email, phone, address, status) VALUES (?, ?, ?, ?, ?)',
      [name, email, phone || null, address || null, status || 'active']
    );
    const [members] = await pool.query('SELECT * FROM members WHERE id = ?', [result.insertId]);
    res.status(201).json(members[0]);
  } catch (err) {
    if (err.code === 'ER_DUP_ENTRY') {
      return res.status(400).json({ message: 'Email already exists.' });
    }
    console.error(err);
    res.status(500).json({ message: 'Failed to create member.' });
  }
});

router.put('/:id', async (req, res) => {
  try {
    const { name, email, phone, address, status } = req.body;
    const [existing] = await pool.query('SELECT * FROM members WHERE id = ?', [req.params.id]);
    if (existing.length === 0) return res.status(404).json({ message: 'Member not found.' });

    const m = existing[0];
    await pool.query(
      'UPDATE members SET name=?, email=?, phone=?, address=?, status=? WHERE id=?',
      [
        name || m.name,
        email || m.email,
        phone !== undefined ? phone : m.phone,
        address !== undefined ? address : m.address,
        status || m.status,
        req.params.id,
      ]
    );
    const [members] = await pool.query('SELECT * FROM members WHERE id = ?', [req.params.id]);
    res.json(members[0]);
  } catch (err) {
    console.error(err);
    res.status(500).json({ message: 'Failed to update member.' });
  }
});

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

module.exports = router;
