const express = require('express');
const router = express.Router();
const {
  getAllCustomers,
  createCustomer,
  updateCustomer,
  deleteCustomer
} = require('../config/db');

// GET /api/customers - List all customers
router.get('/', async (req, res) => {
  try {
    const customers = await getAllCustomers();
    res.json({ success: true, customers });
  } catch (error) {
    console.error('Error fetching customers:', error);
    res.status(500).json({ success: false, message: 'Failed to fetch customers' });
  }
});

// POST /api/customers - Create new customer
router.post('/', async (req, res) => {
  try {
    const { name, company, email, phone, address } = req.body;
    if (!name || !phone) {
      return res.status(400).json({ success: false, message: 'Customer name and phone number are required' });
    }

    const newCustomer = await createCustomer({ name, company, email, phone, address });
    res.status(201).json({ success: true, customer: newCustomer });
  } catch (error) {
    console.error('Error creating customer:', error);
    res.status(500).json({ success: false, message: 'Failed to create customer' });
  }
});

// PUT /api/customers/:id - Update customer
router.put('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    const { name, company, email, phone, address } = req.body;
    if (!name || !phone) {
      return res.status(400).json({ success: false, message: 'Customer name and phone number are required' });
    }

    const updated = await updateCustomer(id, { name, company, email, phone, address });
    res.json({ success: true, customer: updated });
  } catch (error) {
    console.error('Error updating customer:', error);
    res.status(500).json({ success: false, message: 'Failed to update customer' });
  }
});

// DELETE /api/customers/:id - Delete customer
router.delete('/:id', async (req, res) => {
  try {
    const { id } = req.params;
    await deleteCustomer(id);
    res.json({ success: true, message: 'Customer deleted successfully' });
  } catch (error) {
    console.error('Error deleting customer:', error);
    res.status(500).json({ success: false, message: 'Failed to delete customer' });
  }
});

module.exports = router;
