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 buildDateBoundary = (dateValue, boundary) => {
  if (!dateValue) {
    return null;
  }

  const timeSuffix =
    boundary === 'start' ? 'T00:00:00.000Z' : 'T23:59:59.999Z';

  return new Date(`${dateValue}${timeSuffix}`);
};

router.get('/report', passport.authenticate('jwt', { session: false }), wrapAsync(async (req, res) => {
  const { startDate, endDate, classId } = req.query;

  const where = {};
  const start = buildDateBoundary(startDate, 'start');
  const end = buildDateBoundary(endDate, 'end');

  if (start && end && start > end) {
    return res.status(400).json({ message: 'startDate must be on or before endDate' });
  }

  if (start || end) {
    where.work_date = {};

    if (start) {
      where.work_date[Op.gte] = start;
    }

    if (end) {
      where.work_date[Op.lte] = end;
    }
  }

  if (classId) {
    where.workersCompClassId = classId;
  }

  const jobLogs = await db.job_logs.findAll({
    where,
    include: [
      { model: db.workers_comp_classes, as: 'workersCompClass' },
      { model: db.pay_types, as: 'pay_type' },
      { model: db.users, as: 'employee' },
    ],
  });

  const totalsByClass = {};
  let totalComp = 0;

  jobLogs.forEach((log) => {
    if (!log.workersCompClass || !log.pay_type) return;

    let employeePay = 0;
    if (log.pay_type.pay_method === 'hourly') {
      employeePay = Number(log.hours_conducted || 0) * Number(log.pay_type.hourly_rate || 0);
    } else if (log.pay_type.pay_method === 'commission') {
      employeePay = Number(log.client_paid || 0) * (Number(log.pay_type.commission_rate || 0) / 100);
    }

    const compAmount = employeePay * (Number(log.workersCompClass.percentage || 0) / 100);
    const className = log.workersCompClass.name;

    if (!totalsByClass[className]) totalsByClass[className] = 0;
    totalsByClass[className] += compAmount;
    totalComp += compAmount;
  });

  res.json({ totalsByClass, totalComp });
}));

module.exports = router;
