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

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

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

    if (search) {
      query += ' WHERE fullname LIKE ? OR phone_number LIKE ? OR email LIKE ?';
      const searchTerm = `%${search}%`;
      params = [searchTerm, searchTerm, searchTerm];
    }

    query += ' ORDER BY registration_date DESC';
    const [customers] = await pool.query(query, params);
    res.json(customers);
  } catch (error) {
    console.error('Get customers error:', error);
    res.status(500).json({ message: 'Failed to fetch customers.' });
  }
});

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

router.post('/', async (req, res) => {
  try {
    const { fullname, phone_number, email, address } = req.body;
    if (!fullname || !phone_number) {
      return res.status(400).json({ message: 'Full name and phone number are required.' });
    }

    const [result] = await pool.query(
      'INSERT INTO customers (fullname, phone_number, email, address) VALUES (?, ?, ?, ?)',
      [fullname, phone_number, email || null, address || null]
    );

    const [newCustomer] = await pool.query('SELECT * FROM customers WHERE customer_id = ?', [result.insertId]);
    res.status(201).json(newCustomer[0]);
  } catch (error) {
    console.error('Create customer error:', error);
    res.status(500).json({ message: 'Failed to create customer.' });
  }
});

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

    await pool.query(
      'UPDATE customers SET fullname = ?, phone_number = ?, email = ?, address = ? WHERE customer_id = ?',
      [fullname, phone_number, email, address, req.params.id]
    );

    const [updated] = await pool.query('SELECT * FROM customers WHERE customer_id = ?', [req.params.id]);
    res.json(updated[0]);
  } catch (error) {
    console.error('Update customer error:', error);
    res.status(500).json({ message: 'Failed to update customer.' });
  }
});

router.delete('/:id', async (req, res) => {
  try {
    const [existing] = await pool.query('SELECT * FROM customers WHERE customer_id = ?', [req.params.id]);
    if (existing.length === 0) {
      return res.status(404).json({ message: 'Customer not found.' });
    }

    const [sales] = await pool.query('SELECT * FROM sales WHERE customer_id = ?', [req.params.id]);
    if (sales.length > 0) {
      return res.status(400).json({ message: 'Cannot delete customer with existing sales records.' });
    }

    await pool.query('DELETE FROM customers WHERE customer_id = ?', [req.params.id]);
    res.json({ message: 'Customer deleted successfully.' });
  } catch (error) {
    console.error('Delete customer error:', error);
    res.status(500).json({ message: 'Failed to delete customer.' });
  }
});

module.exports = router;
