import i18next from "i18next";
import { bodyshopHasDmsKey } from "../../utils/dmsUtils.js";

export const CalculateAllocationsTotals = (bodyshop, joblines, timetickets, adjustments = []) => {
  const responsibilitycenters = bodyshop.md_responsibility_centers;
  const jobCodes = joblines.map((item) => item.mod_lbr_ty);
  //.filter((value, index, self) => self.indexOf(value) === index && !!value);
  const ticketCodes = timetickets.map((item) => item.ciecacode);
  //.filter((value, index, self) => self.indexOf(value) === index && !!value);
  const adjustmentCodes = Object.keys(adjustments);
  const allCodes = [...jobCodes, ...ticketCodes, ...adjustmentCodes].filter(
    (value, index, self) => self.indexOf(value) === index && !!value
  );

  const r = allCodes.reduce((acc, value) => {
    const r = {
      opcode: value,
      cost_center: bodyshopHasDmsKey(bodyshop)
        ? i18next.t(`joblines.fields.lbr_types.${value && value.toUpperCase()}`)
        : responsibilitycenters.defaults.costs[value],
      mod_lbr_ty: value,
      total: joblines.reduce((acc2, val2) => {
        return val2.mod_lbr_ty === value ? acc2 + val2.mod_lb_hrs : acc2;
      }, 0),
      adjustments: adjustments[value] || 0,
      claimed: timetickets.reduce((acc3, val3) => {
        return val3.ciecacode === value ? acc3 + val3.productivehrs : acc3;
      }, 0)
    };

    r.difference = r.total + r.adjustments - r.claimed;
    acc.push(r);
    return acc;
  }, []);

  return r;
};
