const db = require('../models');
const { sendResponse, sendError } = require('../utils/response');
const asyncHandler = require('../middlewares/asyncHandler');
const stockLedgerService = require('../services/stockLedgerService');

exports.getStockLedger = asyncHandler(async (req, res) => {
  const {
    companyId,
    plantId,
    materialId,
    storageLocation,
    transactionType,
    referenceType,
    referenceId,
    startDate,
    endDate,
    batchNumber,
    lotNumber,
    page = 1,
    limit = 100
  } = req.query;

  const filters = {
    companyId: companyId || req.user?.companyId,
    plantId,
    materialId,
    storageLocation,
    transactionType,
    referenceType,
    referenceId,
    startDate,
    endDate,
    batchNumber,
    lotNumber,
    page: parseInt(page),
    limit: parseInt(limit)
  };

  const result = await stockLedgerService.getStockLedger(filters);

  sendResponse(res, 200, true, 'Stock ledger retrieved successfully', result);
});

exports.getCurrentBalance = asyncHandler(async (req, res) => {
  const { materialId, storageLocation } = req.query;
  const companyId = req.query.companyId || req.user?.companyId;
  const plantId = req.query.plantId;

  if (!materialId || !companyId || !plantId) {
    return sendError(res, 400, 'Material ID, Company ID, and Plant ID are required');
  }

  const balance = await stockLedgerService.getCurrentBalance(
    companyId,
    plantId,
    materialId,
    storageLocation
  );

  sendResponse(res, 200, true, 'Current balance retrieved successfully', { balance });
});

exports.getCurrentBalances = asyncHandler(async (req, res) => {
  const { materialIds, storageLocation } = req.body;
  const companyId = req.body.companyId || req.user?.companyId;
  const plantId = req.body.plantId;

  if (!materialIds || !Array.isArray(materialIds) || materialIds.length === 0) {
    return sendError(res, 400, 'Material IDs array is required');
  }

  if (!companyId || !plantId) {
    return sendError(res, 400, 'Company ID and Plant ID are required');
  }

  const balances = await stockLedgerService.getCurrentBalances(
    companyId,
    plantId,
    materialIds,
    storageLocation
  );

  sendResponse(res, 200, true, 'Current balances retrieved successfully', balances);
});

exports.getStockMovementSummary = asyncHandler(async (req, res) => {
  const { materialId, startDate, endDate } = req.query;
  const companyId = req.query.companyId || req.user?.companyId;
  const plantId = req.query.plantId;

  if (!materialId || !companyId || !plantId) {
    return sendError(res, 400, 'Material ID, Company ID, and Plant ID are required');
  }

  const summary = await stockLedgerService.getStockMovementSummary(
    companyId,
    plantId,
    materialId,
    startDate,
    endDate
  );

  sendResponse(res, 200, true, 'Stock movement summary retrieved successfully', summary);
});

