/**
 * Reports Controllers
 * Request handlers for report operations
 */

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

/**
 * Get sales report by date
 * Generates sales report filtered by date range
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getSalesReportByDate = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date } = req.query; // Get date filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
  }; // Build filters
  
  // Generate report using service
  const report = await reportService.getSalesReportByDate(filters); // Generate report
  
  // Log report generation
  logger.info('Sales report by date generated', {
    start_date,
    end_date,
    totalSales: report.summary.total_sales,
  });
  
  // Return success response with report data
  return successResponse(res, report, 'Sales report generated successfully'); // Return success response
});

/**
 * Get sales report by product
 * Generates sales report grouped by product
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getSalesReportByProduct = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date, product_id } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
    ...(product_id && { product_id: parseInt(product_id) }), // Add product_id filter if provided
  }; // Build filters
  
  // Generate report using service
  const report = await reportService.getSalesReportByProduct(filters); // Generate report
  
  // Log report generation
  logger.info('Sales report by product generated', {
    start_date,
    end_date,
    product_id,
    totalProducts: report.summary.total_products,
  });
  
  // Return success response with report data
  return successResponse(res, report, 'Sales report by product generated successfully'); // Return success response
});

/**
 * Get sales report by customer
 * Generates sales report grouped by customer
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getSalesReportByCustomer = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date, customer_id } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
    ...(customer_id && { customer_id: parseInt(customer_id) }), // Add customer_id filter if provided
  }; // Build filters
  
  // Generate report using service
  const report = await reportService.getSalesReportByCustomer(filters); // Generate report
  
  // Log report generation
  logger.info('Sales report by customer generated', {
    start_date,
    end_date,
    customer_id,
    totalCustomers: report.summary.total_customers,
  });
  
  // Return success response with report data
  return successResponse(res, report, 'Sales report by customer generated successfully'); // Return success response
});

/**
 * Get sales report by cashier
 * Generates sales report grouped by cashier
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getSalesReportByCashier = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date, user_id } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
    ...(user_id && { user_id: parseInt(user_id) }), // Add user_id filter if provided
  }; // Build filters
  
  // Generate report using service
  const report = await reportService.getSalesReportByCashier(filters); // Generate report
  
  // Log report generation
  logger.info('Sales report by cashier generated', {
    start_date,
    end_date,
    user_id,
    totalCashiers: report.summary.total_cashiers,
  });
  
  // Return success response with report data
  return successResponse(res, report, 'Sales report by cashier generated successfully'); // Return success response
});

/**
 * Get fast-moving products report
 * Retrieves products with highest sales velocity
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getFastMovingProducts = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date, limit } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
    ...(limit && { limit: parseInt(limit) }), // Add limit filter if provided
  }; // Build filters
  
  // Generate report using service
  const products = await reportService.getFastMovingProducts(filters); // Generate report
  
  // Log report generation
  logger.info('Fast-moving products report generated', {
    start_date,
    end_date,
    limit,
    productCount: products.length,
  });
  
  // Return success response with report data
  return successResponse(res, products, 'Fast-moving products report generated successfully'); // Return success response
});

/**
 * Get slow-moving products report
 * Retrieves products with lowest sales velocity
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getSlowMovingProducts = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date, limit } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
    ...(limit && { limit: parseInt(limit) }), // Add limit filter if provided
  }; // Build filters
  
  // Generate report using service
  const products = await reportService.getSlowMovingProducts(filters); // Generate report
  
  // Log report generation
  logger.info('Slow-moving products report generated', {
    start_date,
    end_date,
    limit,
    productCount: products.length,
  });
  
  // Return success response with report data
  return successResponse(res, products, 'Slow-moving products report generated successfully'); // Return success response
});

/**
 * Get low stock items report
 * Retrieves products below reorder level
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getLowStockItems = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { category_id } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(category_id && { category_id: parseInt(category_id) }), // Add category_id filter if provided
  }; // Build filters
  
  // Generate report using service
  const items = await reportService.getLowStockItems(filters); // Generate report
  
  // Log report generation
  logger.info('Low stock items report generated', {
    category_id,
    itemCount: items.length,
  });
  
  // Return success response with report data
  return successResponse(res, items, 'Low stock items report generated successfully'); // Return success response
});

/**
 * Get profit/loss report
 * Calculates profit/loss based on sales revenue and cost of goods sold
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getProfitLossReport = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date } = req.query; // Get date filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
  }; // Build filters
  
  // Generate report using service
  const report = await reportService.getProfitLossReport(filters); // Generate report
  
  // Log report generation
  logger.info('Profit/loss report generated', {
    start_date,
    end_date,
    grossProfit: report.profit.gross_profit,
  });
  
  // Return success response with report data
  return successResponse(res, report, 'Profit/loss report generated successfully'); // Return success response
});

// Tax report removed - tax functionality removed from system
// Shift report removed - shift functionality removed from system

/**
 * Get payment methods report
 * Generates report grouped by payment method (CASH, CARD, MPESA)
 * @param {Object} req - Express request object
 * @param {Object} res - Express response object
 */
const getPaymentMethodsReport = asyncHandler(async (req, res) => {
  // Extract query parameters
  const { start_date, end_date, provider } = req.query; // Get filters
  
  // Build filters object
  const filters = {
    ...(start_date && { start_date }), // Add start_date filter if provided
    ...(end_date && { end_date }), // Add end_date filter if provided
    ...(provider && { provider }), // Add provider filter if provided
  }; // Build filters
  
  // Generate report using service
  const report = await reportService.getPaymentMethodsReport(filters); // Generate report
  
  // Log report generation
  logger.info('Payment methods report generated', {
    start_date,
    end_date,
    provider,
    totalRevenue: report.summary.total_revenue,
  });
  
  // Return success response with report data
  return successResponse(res, report, 'Payment methods report generated successfully'); // Return success response
});

// Export all controllers
module.exports = {
  getSalesReportByDate,
  getSalesReportByProduct,
  getSalesReportByCustomer,
  getSalesReportByCashier,
  getFastMovingProducts,
  getSlowMovingProducts,
  getLowStockItems,
  getProfitLossReport,
  getPaymentMethodsReport,
  // getTaxReport removed - tax functionality removed
  // getShiftReport removed - shift functionality removed
};

