const purchaseRepo = require('../repositories/purchaseRepository');
const { successResponse, errorResponse, paginate } = require('../utils/helpers');
const { logAudit } = require('../middleware/auditLog');

async function getAll(req, res, next) {
  try {
    const { page, limit, startDate, endDate } = req.query;
    const { limit: l, offset, page: p } = paginate(page, limit);
    const { rows, total } = await purchaseRepo.findAll({ limit: l, offset, startDate, endDate });
    return successResponse(res, { data: rows, total, page: p, limit: l, totalPages: Math.ceil(total / l) });
  } catch (err) { next(err); }
}

async function getById(req, res, next) {
  try {
    const purchase = await purchaseRepo.findById(req.params.id);
    if (!purchase) return errorResponse(res, 'Purchase not found', 404);
    return successResponse(res, purchase);
  } catch (err) { next(err); }
}

async function create(req, res, next) {
  try {
    const { purchase_date, notes, items } = req.body;
    if (!items || !items.length) return errorResponse(res, 'Purchase must have at least one item', 400);
    for (const item of items) {
      if (!item.product_id || !item.qty || parseFloat(item.qty) <= 0)
        return errorResponse(res, 'Each item needs valid product_id and qty', 400);
    }
    const purchase = await purchaseRepo.create({
      purchase_date: purchase_date || new Date().toISOString().slice(0, 10),
      notes,
      created_by: req.user.id,
      items,
    });
    await logAudit({ userId: req.user.id, action: 'create_purchase', entity: 'purchases', entityId: purchase.id, newData: purchase, req });
    return successResponse(res, purchase, 'Purchase recorded', 201);
  } catch (err) { next(err); }
}

module.exports = { getAll, getById, create };
