/**
 * Customers Controllers
 * Request handlers for customer operations
 */

// Import customer service functions
const customerService = require('../services');
// Import async handler wrapper
const asyncHandler = require('../../../middlewares/asyncHandler');
// Import response helpers
const { success: successResponse } = require('../../../utils/response');
// Import logger
const logger = require('../../../utils/logger');

/**
 * Create customer
 * Creates a new customer
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createCustomer = asyncHandler(async (req, res) => {
  // Extract customer data from request body
  const customerData = req.body; // Get customer data
  
  // Create customer using service
  const customer = await customerService.createCustomer(customerData); // Create customer
  
  // Log customer creation
  logger.info('Customer created', {
    customerId: customer.id,
    name: customer.name,
    customerType: customer.customer_type,
  });
  
  // Return success response with customer data
  return successResponse(res, customer, 'Customer created successfully', 201); // Return success response
});

/**
 * Get customer by ID
 * Retrieves a customer by ID
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getCustomer = asyncHandler(async (req, res) => {
  // Extract customer ID from request params
  const { id } = req.params; // Get customer ID
  
  // Get customer using service
  const customer = await customerService.getCustomer(parseInt(id)); // Get customer
  
  // Return success response with customer data
  return successResponse(res, customer, 'Customer retrieved successfully'); // Return success response
});

/**
 * Update customer
 * Updates an existing customer
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const updateCustomer = asyncHandler(async (req, res) => {
  // Extract customer ID from request params
  const { id } = req.params; // Get customer ID
  // Extract update data from request body
  const updateData = req.body; // Get update data
  
  // Update customer using service
  const customer = await customerService.updateCustomer(parseInt(id), updateData); // Update customer
  
  // Log customer update
  logger.info('Customer updated', {
    customerId: id,
    updateData,
  });
  
  // Return success response with updated customer data
  return successResponse(res, customer, 'Customer updated successfully'); // Return success response
});

/**
 * Delete customer
 * Soft deletes a customer
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const deleteCustomer = asyncHandler(async (req, res) => {
  // Extract customer ID from request params
  const { id } = req.params; // Get customer ID
  
  // Delete customer using service
  await customerService.deleteCustomer(parseInt(id)); // Delete customer
  
  // Log customer deletion
  logger.info('Customer deleted', {
    customerId: id,
  });
  
  // Return success response
  return successResponse(res, null, 'Customer deleted successfully'); // Return success response
});

/**
 * List customers
 * Lists customers with optional filters
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const listCustomers = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { customer_type, active, price_list_id, search, page, limit } = req.query; // Get query params
  
  // Build filters object
  const filters = {
    ...(customer_type && { customer_type }), // Add customer_type filter if provided
    ...(active !== undefined && { active: active === 'true' }), // Add active filter if provided
    ...(price_list_id && { price_list_id: parseInt(price_list_id) }), // Add price_list_id filter if provided
    ...(search && { search }), // Add search filter if provided
  }; // Build filters
  
  // Build pagination object
  const pagination = {
    ...(page && { page }), // Add page if provided
    ...(limit && { limit }), // Add limit if provided
  }; // Build pagination
  
  // List customers using service
  const result = await customerService.listCustomers(filters, pagination); // List customers
  
  // Return success response with customers and pagination
  return successResponse(res, result, 'Customers retrieved successfully'); // Return success response
});

/**
 * Search customers
 * Searches customers by name or KRA PIN
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const searchCustomers = asyncHandler(async (req, res) => {
  // Extract search term from query
  const { q, limit } = req.query; // Get search term and limit
  
  // Validate search term
  if (!q) {
    return successResponse(res, [], 'Search term is required'); // Return empty array if no search term
  }
  
  // Search customers using service
  const customers = await customerService.searchCustomers(q, { limit }); // Search customers
  
  // Return success response with customers
  return successResponse(res, customers, 'Customers found successfully'); // Return success response
});

// Export all controllers
module.exports = {
  createCustomer,
  getCustomer,
  updateCustomer,
  deleteCustomer,
  listCustomers,
  searchCustomers,
};
