/**
 * Pricing Controllers
 * Request handlers for pricing operations
 */

// Import pricing service functions
const pricingService = 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');

// ============================================
// Price List Controllers
// ============================================

/**
 * Create price list
 * Creates a new price list
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createPriceList = asyncHandler(async (req, res) => {
  // Extract price list data from request body
  const priceListData = req.body; // Get price list data
  
  // Create price list using service
  const priceList = await pricingService.createPriceList(priceListData); // Create price list
  
  // Log price list creation
  logger.info('Price list created', {
    priceListId: priceList.id,
    name: priceList.name,
    code: priceList.code,
  });
  
  // Return success response with price list data
  return successResponse(res, priceList, 'Price list created successfully', 201); // Return success response
});

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

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

/**
 * Delete price list
 * Deletes a price list
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const deletePriceList = asyncHandler(async (req, res) => {
  // Extract price list ID from request params
  const { id } = req.params; // Get price list ID
  
  // Delete price list using service
  await pricingService.deletePriceList(parseInt(id)); // Delete price list
  
  // Log price list deletion
  logger.info('Price list deleted', {
    priceListId: id,
  });
  
  // Return success response
  return successResponse(res, null, 'Price list deleted successfully'); // Return success response
});

/**
 * List price lists
 * Retrieves paginated list of price lists with filters
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const listPriceLists = asyncHandler(async (req, res) => {
  // Extract query parameters
  const {
    page = 1, // Page number (default: 1)
    limit = 10, // Items per page (default: 10)
    price_list_type, // Filter by price list type
    active, // Filter by active status
  } = req.query; // Extract query parameters
  
  // Build options object
  const options = {
    page: parseInt(page), // Convert to integer
    limit: parseInt(limit), // Convert to integer
    priceListType: price_list_type || null, // Price list type filter
    active: active !== undefined ? (active === 'true') : null, // Convert to boolean if provided
  };
  
  // List price lists using service
  const result = await pricingService.listPriceLists(options); // List price lists
  
  // Return success response with price lists and pagination
  return successResponse(res, result, 'Price lists retrieved successfully'); // Return success response
});

/**
 * Get default price list
 * Retrieves the default price list
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getDefaultPriceList = asyncHandler(async (req, res) => {
  // Get default price list using service
  const priceList = await pricingService.getDefaultPriceList(); // Get default price list
  
  // If no default price list found, return null
  if (!priceList) {
    return successResponse(res, null, 'No default price list found'); // Return null
  }
  
  // Return success response with default price list
  return successResponse(res, priceList, 'Default price list retrieved successfully'); // Return success response
});

// ============================================
// Product Price Controllers
// ============================================

/**
 * Create product price
 * Creates a new product price
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const createProductPrice = asyncHandler(async (req, res) => {
  // Extract product price data from request body
  const priceData = req.body; // Get price data
  
  // Create product price using service
  const productPrice = await pricingService.createProductPrice(priceData); // Create product price
  
  // Log product price creation
  logger.info('Product price created', {
    priceId: productPrice.id,
    productId: priceData.product_id,
    
    priceListId: priceData.price_list_id,
  });
  
  // Return success response with product price data
  return successResponse(res, productPrice, 'Product price created successfully', 201); // Return success response
});

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

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

/**
 * Delete product price
 * Deletes a product price
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const deleteProductPrice = asyncHandler(async (req, res) => {
  // Extract product price ID from request params
  const { id } = req.params; // Get product price ID
  
  // Delete product price using service
  await pricingService.deleteProductPrice(parseInt(id)); // Delete product price
  
  // Log product price deletion
  logger.info('Product price deleted', {
    priceId: id,
  });
  
  // Return success response
  return successResponse(res, null, 'Product price deleted successfully'); // Return success response
});

/**
 * List product prices
 * Retrieves paginated list of product prices with filters
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const listProductPrices = asyncHandler(async (req, res) => {
  // Extract query parameters
  const {
    page = 1, // Page number (default: 1)
    limit = 10, // Items per page (default: 10)
    price_list_id, // Filter by price list ID
    product_id, // Filter by product ID
    // variant_id removed
    active, // Filter by active status
  } = req.query; // Extract query parameters
  
  // Build options object
  const options = {
    page: parseInt(page), // Convert to integer
    limit: parseInt(limit), // Convert to integer
    priceListId: price_list_id ? parseInt(price_list_id) : null, // Convert to integer if provided
    productId: product_id ? parseInt(product_id) : null, // Convert to integer if provided
    // variantId removed
    active: active !== undefined ? (active === 'true') : null, // Convert to boolean if provided
  };
  
  // List product prices using service
  const result = await pricingService.listProductPrices(options); // List product prices
  
  // Return success response with product prices and pagination
  return successResponse(res, result, 'Product prices retrieved successfully'); // Return success response
});

/**
 * Get price for product
 * Retrieves the applicable price for a product
 * Supports per-product pricing (product_id required)
 * Per-group pricing can be achieved using different price lists for different product groups/categories
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getPrice = asyncHandler(async (req, res) => {
  // Extract query parameters
  const {
    product_id, // Product ID
    // variant_id removed
    quantity = 1, // Quantity (default: 1)
    price_list_id, // Price list ID (optional)
  } = req.query; // Extract query parameters
  
  // Get price using service
  const price = await pricingService.getPrice(
    parseInt(product_id), // Convert to integer
    // variant_id removed
    parseFloat(quantity), // Convert to float
    price_list_id ? parseInt(price_list_id) : null // Convert to integer if provided
  ); // Get price
  
  // Return success response with price data
  return successResponse(res, price, 'Price retrieved successfully'); // Return success response
});

/**
 * Get price for customer
 * Retrieves the applicable price for a product for a specific customer
 * Note: Since customer registration is removed, all sales are walk-in (customer_id = null)
 * This function is kept for future customer-specific pricing via price lists
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getPriceForCustomer = asyncHandler(async (req, res) => {
  // Extract query parameters
  const {
    product_id, // Product ID
    // variant_id removed
    quantity = 1, // Quantity (default: 1)
    customer_id, // Customer ID (optional)
  } = req.query; // Extract query parameters
  
  // Get price for customer using service
  const price = await pricingService.getPriceForCustomer(
    parseInt(product_id), // Convert to integer
    // variant_id removed
    parseFloat(quantity), // Convert to float
    customer_id ? parseInt(customer_id) : null // Convert to integer if provided
  ); // Get price
  
  // Return success response with price data
  return successResponse(res, price, 'Price for customer retrieved successfully'); // Return success response
});

// Export controllers
module.exports = {
  // Price list controllers
  createPriceList, // Create price list controller
  getPriceList, // Get price list controller
  updatePriceList, // Update price list controller
  deletePriceList, // Delete price list controller
  listPriceLists, // List price lists controller
  getDefaultPriceList, // Get default price list controller
  // Product price controllers
  createProductPrice, // Create product price controller
  getProductPrice, // Get product price controller
  updateProductPrice, // Update product price controller
  deleteProductPrice, // Delete product price controller
  listProductPrices, // List product prices controller
  getPrice, // Get price controller
  getPriceForCustomer, // Get price for customer controller
};

