/**
 * Returns Controllers
 * Request handlers for return operations
 */

// Import return service functions
const returnService = 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 return
 * Creates a new return with items
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createReturn = asyncHandler(async (req, res) => {
  // Extract return data from request body
  const returnData = req.body; // Get return data
  // Extract user ID from request (set by auth middleware)
  const userId = req.user.id; // Get user ID from authenticated user
  
  // Create return using service
  const returnRecord = await returnService.createReturn(returnData, userId); // Create return
  
  // Log return creation
  logger.info('Return created', {
    returnId: returnRecord.id,
    saleId: returnRecord.sale_id,
    itemsCount: returnRecord.items.length,
  });
  
  // Return success response with return data
  return successResponse(res, returnRecord, 'Return created successfully', 201); // Return success response
});

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

/**
 * List returns
 * Lists returns with optional filters
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const listReturns = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { sale_id, status, page, limit, start_date, end_date } = req.query; // Get query params
  
  // Build filters object
  const filters = {
    ...(sale_id && { sale_id: parseInt(sale_id) }), // Add sale_id filter if provided
    ...(status && { status }), // Add status filter if provided
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date 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 returns using service
  const result = await returnService.listReturns(filters, pagination); // List returns
  
  // Return success response with returns and pagination
  return successResponse(res, result, 'Returns retrieved successfully'); // Return success response
});

/**
 * Complete return
 * Completes a return by updating inventory and generating credit note
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const completeReturn = asyncHandler(async (req, res) => {
  // Extract return ID from request params
  const { id } = req.params; // Get return ID
  // Extract user ID from request (set by auth middleware)
  const userId = req.user.id; // Get user ID from authenticated user
  // Extract refund data from request body
  const {
    refund_method,
    refund_amount,
    replacement_product_id,
    refund_reference,
  } = req.body; // Get refund data
  
  // Build refund data object
  const refundData = {
    ...(refund_method && { refund_method }), // Add refund_method if provided
    ...(refund_amount !== undefined && { refund_amount }), // Add refund_amount if provided
    ...(replacement_product_id && { replacement_product_id: parseInt(replacement_product_id) }), // Add replacement_product_id if provided
    ...(refund_reference && { refund_reference }), // Add refund_reference if provided
  }; // Build refund data
  
  // Complete return using service
  const returnRecord = await returnService.completeReturn(parseInt(id), userId, refundData); // Complete return
  
  // Log return completion
  logger.info('Return completed', {
    returnId: id,
    creditNoteId: returnRecord.creditNotes?.[0]?.id,
  });
  
  // Return success response with completed return data
  return successResponse(res, returnRecord, 'Return completed successfully'); // Return success response
});

// Export all controllers
module.exports = {
  createReturn,
  getReturn,
  listReturns,
  completeReturn,
};
