/**
 * Report model
 * - Computes aggregated report data.
 */

const { query } = require('./baseModel');

async function getBaseStats({ dateFrom, dateTo }) {
  // Notes:
  // - Using separate queries for clarity and compatibility.
  // - All dates are inclusive.

  const [supplierCount] = await query('SELECT COUNT(*) AS totalSuppliers FROM Supplier');
  const [shipmentCount] = await query(
    'SELECT COUNT(*) AS totalShipments FROM Shipment WHERE shipmentDate BETWEEN ? AND ?',
    [dateFrom, dateTo]
  );
  const [deliveryCount] = await query(
    'SELECT COUNT(*) AS totalDeliveries FROM Delivery WHERE deliveryDate BETWEEN ? AND ?',
    [dateFrom, dateTo]
  );

  const deliveryStatusRows = await query(
    `SELECT deliveryStatus, COUNT(*) AS count
     FROM Delivery
     WHERE deliveryDate BETWEEN ? AND ?
     GROUP BY deliveryStatus`,
    [dateFrom, dateTo]
  );

  const shipmentStatusRows = await query(
    `SELECT shipmentStatus, COUNT(*) AS count
     FROM Shipment
     WHERE shipmentDate BETWEEN ? AND ?
     GROUP BY shipmentStatus`,
    [dateFrom, dateTo]
  );

  return {
    totalSuppliers: supplierCount.totalSuppliers,
    totalShipments: shipmentCount.totalShipments,
    totalDeliveries: deliveryCount.totalDeliveries,
    deliveryStatusSummary: deliveryStatusRows.reduce((acc, row) => {
      acc[row.deliveryStatus] = row.count;
      return acc;
    }, {}),
    shipmentStatusSummary: shipmentStatusRows.reduce((acc, row) => {
      acc[row.shipmentStatus] = row.count;
      return acc;
    }, {})
  };
}

module.exports = { getBaseStats };

