const express = require('express');
const router = express.Router();
const passport = require('passport');
const db = require('../db/models');
const { wrapAsync } = require('../helpers');
const { Op } = require('sequelize');

const getDateBoundary = (date, boundary) =>
  new Date(`${date}T${boundary === 'start' ? '00:00:00.000' : '23:59:59.999'}Z`);

router.post('/', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
  const { startDate, endDate, employeeId } = req.body;

  const where = {};
  if (startDate || endDate) {
    where.createdAt = {};
    if (startDate) where.createdAt[Op.gte] = getDateBoundary(startDate, 'start');
    if (endDate) where.createdAt[Op.lte] = getDateBoundary(endDate, 'end');
  }
  if (employeeId) {
    where.employeeId = employeeId;
  }

  const lineItems = await db.payroll_line_items.findAll({
    where,
    include: [{ model: db.users, as: 'employee' }]
  });

  const summary = lineItems.reduce((acc, item) => {
    acc.totalGrossPay += parseFloat(item.gross_pay || 0);
    acc.totalHours += parseFloat(item.total_hours || 0);
    acc.totalWorkersComp += parseFloat(item.workers_comp_amount || 0);
    return acc;
  }, { totalGrossPay: 0, totalHours: 0, totalWorkersComp: 0 });

  res.json({ lineItems, summary });
}));

module.exports = router;
