const Dinero = require("dinero.js");
const queries = require("../graphql-client/queries");
const logger = require("../utils/logger");
const InstanceMgr = require("../utils/instanceMgr").default;

//****************************************************** */
//****************************************************** */
//****************************************************** */
//****************************************************** */
//****************************************************** */
//THIS IS THE USA/ROME REQUIRED JOB TOTALS CALCULATION.
//****************************************************** */
//****************************************************** */
//****************************************************** */
//****************************************************** */

// Dinero.defaultCurrency = "USD";
// Dinero.globalLocale = "en-CA";
Dinero.globalRoundingMode = "HALF_EVEN";

exports.totalsSsu = async function (req, res) {
  const { id } = req.body;

  const BearerToken = req.BearerToken;
  const client = req.userGraphQLClient;

  logger.log("job-totals-ssu-USA", "debug", req?.user?.email, id);

  try {
    const job = await client.setHeaders({ Authorization: BearerToken }).request(queries.GET_JOB_BY_PK, {
      id: id
    });

    const newTotals = await TotalsServerSide({ body: { job: job.jobs_by_pk, client: client } });

    const result = await client.setHeaders({ Authorization: BearerToken }).request(queries.UPDATE_JOB, {
      jobId: id,
      job: {
        clm_total: newTotals.totals.total_repairs.toFormat("0.00"),
        owner_owing: newTotals.totals.custPayable.total.toFormat("0.00"),
        job_totals: newTotals
        //queued_for_parts: true,
      }
    });

    if (!result) {
      throw new Error("Failed to update job totals");
    }

    res.status(200).json({ success: true });
  } catch (error) {
    logger.log("job-totals-ssu-USA-error", "error", req?.user?.email, id, {
      jobid: id,
      error: error.message,
      stack: error.stack
    });
    res.status(503).json({
      error: "Failed to calculate totals",
      message: error?.message || "Unknown error"
    });
  }
};

//IMPORTANT*** These two functions MUST be mirrored.
async function TotalsServerSide(req) {
  const { job, client } = req.body;
  await AtsAdjustmentsIfRequired({ job: job, client: client, user: req?.user });

  try {
    let ret = {
      rates: await CalculateRatesTotals({ job, client }),
      parts: CalculatePartsTotals(job.joblines, job.parts_tax_rates, job)
    };
    ret.additional = CalculateAdditional(job);
    ret.totals = CalculateTaxesTotals(job, ret);

    //If we don't have the CIECA_TTL, we can't scrub. E.g. a private estimate.
    if (job.cieca_ttl) {
      // Sub total scrubbbing.
      const emsTotal =
        job.cieca_ttl.data.n_ttl_amt === job.cieca_ttl.data.g_ttl_amt //It looks like sometimes, gross and net are the same, but they shouldn't be.
          ? job.cieca_ttl.data.n_ttl_amt - job.cieca_ttl.data.g_tax
          : job.cieca_ttl.data.g_ttl_amt - job.cieca_ttl.data.g_tax; //If they are, adjust the gross total down by the tax amount.
      const ttlDifference =
        emsTotal -
        ret.totals.subtotal
          .add(
            Dinero({
              amount: Math.round((job.adjustment_bottom_line || 0) * 100)
            }).multiply(-1) //Add back in the adjustment to the subtotal. We don't want to scrub it twice.
          )
          .getAmount() /
          100;

      if (Math.abs(ttlDifference) > 0.0) {
        //If difference is greater than a pennny, we need to adjust it.
        ret.totals.ttl_adjustment = Dinero({ amount: Math.round(ttlDifference * 100) });
        ret.totals.subtotal = ret.totals.subtotal.add(ret.totals.ttl_adjustment);
        ret.totals.total_repairs = ret.totals.total_repairs.add(ret.totals.ttl_adjustment);
        ret.totals.net_repairs = ret.totals.net_repairs.add(ret.totals.ttl_adjustment);
        logger.log("job-totals-USA-ttl-adj", "debug", null, job.id, {
          adjAmount: ttlDifference
        });
      }

      //Taxes Scrubbing
      const emsTaxTotal = job.cieca_ttl.data.g_tax;
      const totalUsTaxes =
        (ret.totals.us_sales_tax_breakdown.ty1Tax.getAmount() +
          ret.totals.us_sales_tax_breakdown.ty2Tax.getAmount() +
          ret.totals.us_sales_tax_breakdown.ty3Tax.getAmount() +
          ret.totals.us_sales_tax_breakdown.ty4Tax.getAmount() +
          ret.totals.us_sales_tax_breakdown.ty5Tax.getAmount()) /
        100;
      const ttlTaxDifference = emsTaxTotal - totalUsTaxes;

      if (Math.abs(ttlTaxDifference) > 0.0) {
        //If difference is greater than a pennny, we need to adjust it.
        ret.totals.ttl_tax_adjustment = Dinero({ amount: Math.round(ttlTaxDifference * 100) });
        ret.totals.total_repairs = ret.totals.total_repairs.add(ret.totals.ttl_tax_adjustment);
        ret.totals.net_repairs = ret.totals.net_repairs.add(ret.totals.ttl_tax_adjustment);

        if (Math.abs(totalUsTaxes) === 0) {
          const laborRates = Object.values(job.cieca_pfl)
            .map((v) => v.lbr_taxp)
            .filter((v) => v != null);
          const materialRates = Object.values(job.materials)
            .map((v) => v.mat_taxp)
            .filter((v) => v != null);
          const partsRates = Object.values(job.parts_tax_rates)
            .map((v) => {
              const field = v.prt_tax_rt ?? v.part_tax_rt;
              if (field == null) return null;
              const raw = typeof field === "object" ? field.parsedValue : field;
              return raw != null ? raw * 100 : null;
            })
            .filter((v) => v != null);
          const taxRate = Math.max(...laborRates, ...materialRates, ...partsRates);

          if (taxRate > 0) {
            ret.totals.taxableAmounts.total = Dinero({
              amount: Math.round((emsTaxTotal / (taxRate > 1 ? taxRate / 100 : taxRate)) * 100)
            });
          }
        } else {
          ret.totals.taxableAmounts.total = ret.totals.taxableAmounts.total.multiply(emsTaxTotal).divide(totalUsTaxes);
        }

        logger.log("job-totals-USA-ttl-tax-adj", "debug", null, job.id, {
          adjAmount: ttlTaxDifference
        });
      }
    }

    return ret;
  } catch (error) {
    logger.log("job-totals-ssu-USA-error", "error", req.user?.email, job.id, {
      jobid: job.id,
      error: error.message,
      stack: error.stack
    });
    throw error;
  }
}

// Exported for testing purposes.
exports.TotalsServerSide = TotalsServerSide;

async function Totals(req, res) {
  const { job, id } = req.body;

  const logger = req.logger;
  const client = req.userGraphQLClient;

  logger.log("job-totals-ssu-USA", "debug", req?.user?.email, job.id, {
    jobid: job.id,
    id: id
  });

  await AtsAdjustmentsIfRequired({ job, client, user: req.user });

  try {
    let ret = {
      rates: await CalculateRatesTotals({ job, client }),
      parts: CalculatePartsTotals(job.joblines, job.parts_tax_rates, job)
    };
    ret.additional = CalculateAdditional(job);
    ret.totals = CalculateTaxesTotals(job, ret);

    res.status(200).json(ret);
  } catch (error) {
    logger.log("job-totals-ssu-USA-error", "error", req?.user?.email, job.id, {
      jobid: job.id,
      error: error.message,
      stack: error.stack
    });
    res.status(400).send(JSON.stringify(error));
  }
}

async function AtsAdjustmentsIfRequired({ job, client, user }) {
  if (job.auto_add_ats || job.flat_rate_ats) {
    let atsAmount = 0;
    let atsLineIndex = null;

    //Check if ATS should be automatically added.
    if (job.auto_add_ats) {
      const excludedLaborTypes = new Set(["LAA", "LAG", "LAS", "LAU", "LA1", "LA2", "LA3", "LA4"]);

      //Get the total sum of hours that should be the ATS amount.
      //Check to see if an ATS line exists.
      const atsHours = job.joblines.reduce((acc, val, index) => {
        if (val.line_desc?.toLowerCase() === "ats amount") {
          atsLineIndex = index;
        }

        if (!excludedLaborTypes.has(val.mod_lbr_ty)) {
          acc = acc + val.mod_lb_hrs;
        }

        return acc;
      }, 0);

      atsAmount = atsHours * (job.rate_ats || 0);
    }

    //Check if a Flat Rate ATS should be added.
    if (job.flat_rate_ats) {
      atsLineIndex = ((i) => (i === -1 ? null : i))(
        job.joblines.findIndex((line) => line.line_desc?.toLowerCase() === "ats amount")
      );
      atsAmount = job.rate_ats_flat || 0;
    }

    //If it does not, create one for local calculations and insert it.
    if (atsLineIndex === null) {
      const newAtsLine = {
        jobid: job.id,
        alt_partm: null,
        unq_seq: 0,
        line_ind: "E",
        line_desc: "ATS Amount",
        line_ref: 0.0,
        part_type: null,
        oem_partno: null,
        db_price: 0.0,
        act_price: atsAmount,
        part_qty: 1,
        mod_lbr_ty: null,
        db_hrs: 0.0,
        mod_lb_hrs: 0.0,
        lbr_op: "OP13",
        lbr_amt: 0.0,
        op_code_desc: "ADDITIONAL COSTS",
        status: null,
        location: null,
        tax_part: true,
        db_ref: null,
        manual_line: true,
        prt_dsmk_p: 0.0,
        prt_dsmk_m: 0.0
      };

      try {
        const result = await client.request(queries.INSERT_NEW_JOB_LINE, {
          lineInput: [newAtsLine]
        });

        if (result) {
          job.joblines.push(newAtsLine);
        }
      } catch (error) {
        logger.log("job-totals-ssu-ats-error", "error", user?.email, job.id, {
          jobid: job.id,
          error: error.message,
          stack: error.stack
        });
      }
    }
    //If it does, update it in place, and make sure it is updated for local calculations.
    else {
      try {
        const result = await client.request(queries.UPDATE_JOB_LINE, {
          line: { act_price: atsAmount },
          lineId: job.joblines[atsLineIndex].id
        });
        if (result) {
          job.joblines[atsLineIndex].act_price = atsAmount;
        }
      } catch (error) {
        logger.log("job-totals-ssu-ats-error", "error", user?.email, job.id, {
          jobid: job.id,
          atsLineIndex: atsLineIndex,
          atsAmount: atsAmount,
          jobline: job.joblines[atsLineIndex],
          error: error.message,
          stack: error.stack
        });
      }
    }
  }
}

async function CalculateRatesTotals({ job, client }) {
  const jobLines = job.joblines.filter((jl) => !jl.removed);

  let ret = {
    la1: {
      hours: 0,
      rate: job.rate_la1 || 0
    },
    la2: {
      hours: 0,
      rate: job.rate_la2 || 0
    },
    la3: {
      rate: job.rate_la3 || 0,
      hours: 0
    },
    la4: {
      rate: job.rate_la4 || 0,
      hours: 0
    },
    laa: {
      rate: job.rate_laa || 0,
      hours: 0
    },
    lab: {
      rate: job.rate_lab || 0,
      hours: 0
    },
    lad: {
      rate: job.rate_lad || 0,
      hours: 0
    },
    lae: {
      rate: job.rate_lae || 0,
      hours: 0
    },
    laf: {
      rate: job.rate_laf || 0,
      hours: 0
    },
    lag: {
      rate: job.rate_lag || 0,
      hours: 0
    },
    lam: {
      rate: job.rate_lam || 0,
      hours: 0
    },
    lar: {
      rate: job.rate_lar || 0,
      hours: 0
    },
    las: {
      rate: job.rate_las || 0,
      hours: 0
    },
    lau: {
      rate: job.rate_lau || 0,
      hours: 0
    },
    mapa: {
      rate: job.rate_mapa || 0,
      hours: 0
    },
    mash: {
      rate: job.rate_mash || 0,
      hours: 0
    }
  };

  //Determine if there are MAPA and MASH lines already on the estimate.
  //If there are, don't do anything extra (mitchell estimate)
  //Otherwise, calculate them and add them to the default MAPA and MASH centers.
  let hasMapaLine = false;
  let hasMashLine = false;
  let hasMahwLine = false;
  let hasCustomMahwLine;
  // let mapaOpCodes = ParseCalopCode(job.materials["MAPA"]?.cal_opcode);
  let mashOpCodes = ParseCalopCode(job.materials["MASH"]?.cal_opcode);

  jobLines.forEach((item) => {
    //IO-1317 Use the lines on the estimate if they exist instead.
    if (item.db_ref === "936008") {
      //If either of these DB REFs change, they also need to change in job-totals/job-costing calculations.
      hasMapaLine = true;
      ret["mapa"].total = Dinero({
        amount: Math.round((item.act_price || 0) * 100)
      });
    }
    if (item.db_ref === "936007") {
      hasMashLine = true;
      ret["mash"].total = Dinero({
        amount: Math.round((item.act_price || 0) * 100)
      });
    }
    //We might add a hazardous waste line. So we'll need to make sure we only pick up the CCC one.
    if (
      item.line_desc?.toLowerCase().includes("hazardous waste") &&
      !item.manual_line &&
      item.part_type === null &&
      item.lbr_op !== "OP16" //Seems to be that it is OP16 for sublet lines.
    ) {
      hasMahwLine = item;
    }
    if (item.line_desc?.toLowerCase().includes("hazardous waste") && item.manual_line) {
      hasCustomMahwLine = item;
    }

    if (item.mod_lbr_ty) {
      //Check to see if it has 0 hours and a price instead.
      if (
        item.lbr_op === "OP14" &&
        item.act_price > 0 &&
        (!item.part_type || item.mod_lb_hrs === 0) &&
        !IsAdditionalCost(item)
      ) {
        //Scenario where SGI may pay out hours using a part price.
        if (!ret[item.mod_lbr_ty.toLowerCase()].total) {
          ret[item.mod_lbr_ty.toLowerCase()].base = Dinero();
          ret[item.mod_lbr_ty.toLowerCase()].adjustment = Dinero();
          ret[item.mod_lbr_ty.toLowerCase()].total = Dinero();
        }
        ret[item.mod_lbr_ty.toLowerCase()].total = ret[item.mod_lbr_ty.toLowerCase()].total.add(
          Dinero({ amount: Math.round((item.act_price || 0) * 100) }).multiply(item.part_qty)
        );
      }

      //There's a labor type, assign the hours.
      ret[item.mod_lbr_ty.toLowerCase()].hours = ret[item.mod_lbr_ty.toLowerCase()].hours + item.mod_lb_hrs;

      //Count up the number of materials/paint hours.

      //Following change may be CCC specific.
      if (item.mod_lbr_ty === "LAR") {
        // if (mapaOpCodes.includes(item.lbr_op)) { //Unknown if this is needed. Seems to be ignored.
        ret.mapa.hours = ret.mapa.hours + item.mod_lb_hrs;
        // }
      } else {
        if (mashOpCodes.length === 0 || mashOpCodes.includes(item.lbr_op)) {
          // Added when processing CIECA ID 14A60015 to have materials match.
          ret.mash.hours = ret.mash.hours + item.mod_lb_hrs; //Apparently there may be an exclusion for glass hours in BC.
        }
      }
    }
  });

  let subtotal = Dinero({ amount: 0 });
  let rates_subtotal = Dinero({ amount: 0 });

  for (const property in ret) {
    //Skip calculating mapa and mash if we got the amounts.
    if (!((property === "mapa" && hasMapaLine) || (property === "mash" && hasMashLine))) {
      if (!ret[property].total) {
        ret[property].base = Dinero();
        ret[property].adjustment = Dinero();
        ret[property].total = Dinero();
      }
      let threshold;
      //Check if there is a max for this type.
      if (job.materials && job.materials[property.toUpperCase()]) {
        //

        if (
          job.materials[property.toUpperCase()].cal_maxdlr !== undefined &&
          job.materials[property.toUpperCase()].cal_maxdlr >= 0
        ) {
          //It has an upper threshhold.
          threshold = Dinero({
            amount: Math.round(job.materials[property.toUpperCase()].cal_maxdlr * 100)
          });
        }
      }

      const base = Dinero({
        amount: Math.round((ret[property].rate || 0) * 100)
      }).multiply(ret[property].hours);

      let adjp = 0;
      if (property === "mapa" || property === "mash") {
        if (job.materials[property.toUpperCase()] && job.materials[property.toUpperCase()].mat_adjp) {
          adjp =
            Math.abs(job.materials[property.toUpperCase()].mat_adjp) > 1
              ? job.materials[property.toUpperCase()].mat_adjp
              : job.materials[property.toUpperCase()].mat_adjp * 100; //Adjust mat_adjp to whole number
        }
      } else {
        if (property === "la1" || property === "la2" || property === "la3" || property === "la4") {
          if (job.cieca_pfl["LAU"] && job.cieca_pfl["LAU"].lbr_adjp) {
            adjp =
              Math.abs(job.cieca_pfl["LAU"].lbr_adjp) > 1
                ? job.cieca_pfl["LAU"].lbr_adjp
                : job.cieca_pfl["LAU"].lbr_adjp * 100; //Adjust lbr_adjp to whole number
          }
        } else {
          if (job.cieca_pfl[property.toUpperCase()] && job.cieca_pfl[property.toUpperCase()].lbr_adjp) {
            adjp =
              Math.abs(job.cieca_pfl[property.toUpperCase()].lbr_adjp) > 1
                ? job.cieca_pfl[property.toUpperCase()].lbr_adjp
                : job.cieca_pfl[property.toUpperCase()].lbr_adjp * 100; //Adjust lbr_adjp to whole number
          } else {
            if (job.cieca_pfl["LAB"].lbr_adjp) {
              adjp =
                Math.abs(job.cieca_pfl["LAB"].lbr_adjp) > 1
                  ? job.cieca_pfl["LAB"].lbr_adjp
                  : job.cieca_pfl["LAB"].lbr_adjp * 100; //Adjust lbr_adjp to whole number
            }
          }
        }
      }
      const adjustment = base.percentage(adjp < 0 ? adjp * -1 : adjp).multiply(adjp < 0 ? -1 : 1);
      const total = base.add(adjustment);

      if (threshold && total.greaterThanOrEqual(threshold)) {
        ret[property].total = ret[property].total.add(threshold);
      } else {
        ret[property].base = ret[property].base.add(base);
        ret[property].adjustment = ret[property].adjustment.add(adjustment);
        ret[property].total = ret[property].total.add(total);
      }
    }

    subtotal = subtotal.add(ret[property].total);

    if (property !== "mapa" && property !== "mash") rates_subtotal = rates_subtotal.add(ret[property].total);
  }

  const stlMahw = job.cieca_stl?.data.find((c) => c.ttl_typecd === "MAHW");

  if (stlMahw && stlMahw.ttl_amt !== 0 && (!hasMahwLine || hasMahwLine.act_price !== stlMahw.ttl_amt)) {
    //The Mahw line that has been added doesn't match with what we have in the STL. Add/update the adjusting line so that the balance is correct.

    //Add a hazardous waste material line in case there isn't one on the estimate.
    let newPrice = stlMahw.ttl_amt;
    if (hasCustomMahwLine) {
      //Update it
      job.joblines.forEach((jl) => {
        if (jl.id === hasCustomMahwLine.id) {
          jl.act_price = newPrice;
          jl.manual_line = true;
          jl.tax_part = stlMahw.tax_amt > 0 ? true : false;
        }
      });
      await client.request(queries.UPDATE_JOB_LINE, {
        lineId: hasCustomMahwLine.id,
        line: {
          act_price: newPrice,
          manual_line: true,
          tax_part: stlMahw.tax_amt > 0 ? true : false
        }
      });
    } else {
      const newMahwLine = {
        line_desc: "Hazardous Waste Removal*",
        part_type: null,
        oem_partno: null,
        db_price: 0,
        act_price: newPrice,
        part_qty: 1,
        mod_lbr_ty: "LAB",
        db_hrs: 0,
        mod_lb_hrs: 0,
        lbr_op: "OP0",
        lbr_amt: 0,
        op_code_desc: "REMOVE / REPLACE",
        tax_part: stlMahw.tax_amt > 0 ? true : false,
        db_ref: null,
        manual_line: true,
        jobid: job.id
      };
      job.joblines.push(newMahwLine);
      await client.request(queries.INSERT_NEW_JOB_LINE, {
        lineInput: [newMahwLine]
      });
    }
  }

  //Materials Scrubbing as required by CCC.
  let matTotalLine = job.cieca_stl?.data?.find((l) => l.ttl_typecd === "MAT");
  let shopMatLine = job.cieca_stl?.data?.find((l) => l.ttl_typecd === "MASH");

  if (matTotalLine && shopMatLine) {
    //Check to see if theyre different
    let calcMapaAmount = Dinero({
      amount: Math.round((matTotalLine?.ttl_amt - shopMatLine?.ttl_amt - stlMahw?.ttl_amt) * 100)
    });
    let mapaDifference = calcMapaAmount.subtract(ret.mapa.total);
    if (mapaDifference.getAmount() > 0) {
      //fix it.
      ret.mapa.total = calcMapaAmount;
      //Add the difference to the subt total as well.
      subtotal = subtotal.add(mapaDifference);
    }
  }
  ret.subtotal = subtotal;
  ret.rates_subtotal = rates_subtotal;

  ret.mapa.hasMapaLine = hasMapaLine;
  ret.mash.hasMashLine = hasMashLine;
  return ret;
}

function CalculatePartsTotals(jobLines, parts_tax_rates, job) {
  const jl = jobLines.filter((jl) => !jl.removed);
  const ret = jl.reduce(
    (acc, value) => {
      switch (value.part_type) {
        case "PAS":
        case "PASL":
          return {
            ...acc,
            sublets: {
              ...acc.sublets,
              subtotal: acc.sublets.subtotal.add(
                Dinero({
                  amount: Math.round(value.act_price * 100)
                })
                  .multiply(value.part_qty || 0)
                  .add(
                    ((value.prt_dsmk_m && value.prt_dsmk_m !== 0) || (value.prt_dsmk_p && value.prt_dsmk_p !== 0)) &&
                      DiscountNotAlreadyCounted(value, jl)
                      ? value.prt_dsmk_m
                        ? Dinero({ amount: Math.round(value.prt_dsmk_m * 100) })
                        : Dinero({
                            amount: Math.round(value.act_price * 100)
                          })
                            .multiply(value.part_qty || 0)
                            .percentage(Math.abs(value.prt_dsmk_p || 0))
                            .multiply(value.prt_dsmk_p > 0 ? 1 : -1)
                      : Dinero()
                  )
              )
            }
          };

        default: {
          if (!value.part_type && value.db_ref !== "900510" && value.db_ref !== "900511") return acc;

          const discountAmount =
            ((value.prt_dsmk_m && value.prt_dsmk_m !== 0) || (value.prt_dsmk_p && value.prt_dsmk_p !== 0)) &&
            DiscountNotAlreadyCounted(value, jl)
              ? value.prt_dsmk_m
                ? Dinero({ amount: Math.round(value.prt_dsmk_m * 100) })
                : Dinero({
                    amount: Math.round(value.act_price * 100)
                  })
                    .multiply(value.part_qty || 0)
                    .percentage(Math.abs(value.prt_dsmk_p || 0))
                    .multiply(value.prt_dsmk_p > 0 ? 1 : -1)
              : Dinero();

          return {
            ...acc,
            parts: {
              ...acc.parts,
              prt_dsmk_total: acc.parts.prt_dsmk_total.add(discountAmount),
              ...(value.part_type
                ? {
                    list: {
                      ...acc.parts.list,
                      [value.part_type]:
                        acc.parts.list[value.part_type] && acc.parts.list[value.part_type].total
                          ? {
                              total: acc.parts.list[value.part_type].total
                                .add(
                                  Dinero({
                                    amount: Math.round((value.act_price || 0) * 100)
                                  }).multiply(value.part_qty || 0)
                                )
                                .add(discountAmount)
                            }
                          : {
                              total: Dinero({
                                amount: Math.round((value.act_price || 0) * 100)
                              })
                                .multiply(value.part_qty || 0)
                                .add(discountAmount)
                            }
                    }
                  }
                : {}),
              subtotal: acc.parts.subtotal
                .add(
                  Dinero({
                    amount: Math.round(value.act_price * 100)
                  }).multiply(value.part_qty || 0)
                )
                .add(
                  ((value.prt_dsmk_m && value.prt_dsmk_m !== 0) || (value.prt_dsmk_p && value.prt_dsmk_p !== 0)) &&
                    DiscountNotAlreadyCounted(value, jl)
                    ? value.prt_dsmk_m
                      ? Dinero({ amount: Math.round(value.prt_dsmk_m * 100) })
                      : Dinero({
                          amount: Math.round(value.act_price * 100)
                        })
                          .multiply(value.part_qty || 0)
                          .percentage(Math.abs(value.prt_dsmk_p || 0))
                          .multiply(value.prt_dsmk_p > 0 ? 1 : -1)
                    : Dinero()
                )
            }
          };
        }
      }
    },
    {
      parts: {
        list: {},
        prt_dsmk_total: Dinero(),
        subtotal: Dinero({ amount: 0 }),
        total: Dinero({ amount: 0 })
      },
      sublets: {
        subtotal: Dinero({ amount: 0 }),

        total: Dinero({ amount: 0 })
      }
    }
  );

  //Apply insurance based parts discounts/markups.
  let adjustments = {};
  //Track all adjustments that need to be made.

  //const linesToAdjustForDiscount = [];
  Object.keys(parts_tax_rates).forEach((key) => {
    //Check if there's a discount or a mark up.
    let disc = Dinero(),
      markup = Dinero();

    let discountRate, markupRate;
    if (parts_tax_rates[key].prt_discp !== undefined && parts_tax_rates[key].prt_discp >= 0) {
      //Check if there's any parts in this part type.
      if (ret.parts.list[key] !== undefined) {
        discountRate =
          Math.abs(parts_tax_rates[key].prt_discp) > 1
            ? parts_tax_rates[key].prt_discp
            : parts_tax_rates[key].prt_discp * 100;

        disc = ret.parts.list[key].total.percentage(discountRate).multiply(-1);
      }
    }
    if (parts_tax_rates[key].prt_mkupp !== undefined && parts_tax_rates[key].prt_mkupp >= 0) {
      //Check if there's any parts in this part type.
      if (ret.parts.list[key] !== undefined) {
        markupRate =
          Math.abs(parts_tax_rates[key].prt_mkupp) > 1
            ? parts_tax_rates[key].prt_mkupp
            : parts_tax_rates[key].prt_mkupp * 100; //Seems that mark up is written as decimal not %.

        markup = ret.parts.list[key].total.percentage(markupRate);
      }
    }
    const correspondingCiecaStlTotalLine = job.cieca_stl?.data.find((c) => c.ttl_typecd === key);

    //If the difference is greater than a penny, fix it.
    //This usually ties into whether or not the profile has part type discounts overall in the PFP.
    if (
      correspondingCiecaStlTotalLine &&
      Math.abs(ret.parts.list[key]?.total.getAmount() - correspondingCiecaStlTotalLine.ttl_amt * 100) > 1
    ) {
      let adjustment = disc.add(markup);
      adjustments[key] = adjustment;
      ret.parts.subtotal = ret.parts.subtotal.add(adjustment);
      ret.parts.total = ret.parts.total.add(adjustment);
    }
  });

  return {
    adjustments,
    parts: {
      ...ret.parts,
      total: ret.parts.subtotal
    },
    sublets: {
      ...ret.sublets,
      total: ret.sublets.subtotal
    }
  };
}

function IsAdditionalCost(jobLine) {
  //May be able to use db_ref here to help.
  //936012 is Haz Waste Dispoal
  //936008 is Paint/Materials
  //936007 is Shop/Materials

  //Remove paint and shop mat lines. They're calculated under rates.
  const isPaintOrShopMat = jobLine.db_ref === "936008" || jobLine.db_ref === "936007";

  return (
    (jobLine.lbr_op === "OP13" || //Added to resolve manual job lines coming into other totals because they have no reference.
      (jobLine.part_type === null && (jobLine.act_price || 0) > 0) ||
      (jobLine.db_ref && jobLine.db_ref.startsWith("9360"))) && //This ref works in Canada, but DB_REFS in the US do not fill in.
    !isPaintOrShopMat
  );
}

function CalculateAdditional(job) {
  const stlTowing = job.cieca_stl?.data.find((c) => c.ttl_type === "OTTW");
  const stlStorage = job.cieca_stl?.data.find((c) => c.ttl_type === "OTST");

  let ret = {
    additionalCosts: null,
    additionalCostItems: [],
    adjustments: null,
    towing: Dinero(),
    shipping: Dinero(),
    storage: null,
    pvrt: null,
    total: null
  };
  ret.towing = stlTowing
    ? Dinero({ amount: Math.round(stlTowing.ttl_amt * 100) })
    : Dinero({
        amount: Math.round((job.towing_payable || 0) * 100)
      });

  ret.additionalCosts = job.joblines
    .filter((jl) => !jl.removed && IsAdditionalCost(jl))
    .reduce((acc, val) => {
      const lineValue = Dinero({
        amount: Math.round((val.act_price || 0) * 100)
      }).multiply(val.part_qty);

      if (val.db_ref === "936004") {
        //Shipping line IO-1921.
        ret.shipping = ret.shipping.add(lineValue);
      }

      if (val.line_desc.toLowerCase().includes("towing")) {
        ret.towing = ret.towing.add(lineValue);
        return acc;
      } else {
        ret.additionalCostItems.push({ key: val.line_desc, total: lineValue });
        return acc.add(lineValue);
      }
    }, Dinero());
  ret.adjustments = Dinero({
    amount: Math.round((job.adjustment_bottom_line || 0) * 100)
  });
  ret.storage = stlStorage
    ? Dinero({ amount: Math.round(stlStorage.ttl_amt * 100) })
    : Dinero({
        amount: Math.round((job.storage_payable || 0) * 100)
      });
  ret.pvrt = Dinero({
    amount: Math.round((job.ca_bc_pvrt || 0) * 100)
  });
  ret.total = ret.additionalCosts
    .add(ret.adjustments) //IO-813 Adjustment takes care of GST & PST at labor rate.
    .add(ret.towing)
    .add(ret.storage);

  return ret;
}

function CalculateTaxesTotals(job, otherTotals) {
  const subtotal = otherTotals.parts.parts.subtotal
    .add(otherTotals.parts.sublets.subtotal)
    .add(otherTotals.rates.subtotal) //No longer using just rates subtotal to include mapa/mash.
    .add(otherTotals.additional.total);

  //Potential issue here with Sublet Calculation. Sublets are calculated under labor in Mitchell, but it's done in IO
  //Under the parts rates.

  let stateTax = Dinero();
  // let additionalItemsTax = Dinero(); //This is not used.
  let us_sales_tax_breakdown;

  // This is not referenced in the code base.
  //Audatex sends additional glass part types. IO-774
  // const BackupGlassTax =
  //   job.parts_tax_rates &&
  //   (job.parts_tax_rates.PAGD ||
  //     job.parts_tax_rates.PAGF ||
  //     job.parts_tax_rates.PAGP ||
  //     job.parts_tax_rates.PAGQ ||
  //     job.parts_tax_rates.PAGR);

  const taxableAmounts = {
    PAA: Dinero(),
    PAE: Dinero(),
    PAN: Dinero(),
    PAL: Dinero(),
    PAR: Dinero(),
    PAC: Dinero(),
    PAG: Dinero(),
    PAO: Dinero(),
    PAS: Dinero(),
    PASL: Dinero(),
    PAP: Dinero(),
    PAM: Dinero(),

    LA1: Dinero(),
    LA2: Dinero(),
    LA3: Dinero(),
    LA4: Dinero(),
    LAU: Dinero(),
    LAA: Dinero(),
    LAB: Dinero(),
    LAD: Dinero(),
    LAE: Dinero(),
    LAF: Dinero(),
    LAG: Dinero(),
    LAM: Dinero(),
    LAR: Dinero(),
    LAS: Dinero(),

    MAPA: Dinero(),
    MASH: Dinero(),
    TOW: Dinero(),
    STOR: Dinero()
  };

  const pfp = job.parts_tax_rates;

  //For each line, determine if it's taxable, and if it is, add the line amount to the taxable amounts total.
  job.joblines
    .filter((jl) => !jl.removed)
    .forEach((val) => {
      if (!val.tax_part) return;
      if (!val.part_type && IsAdditionalCost(val)) {
        taxableAmounts.PAO = taxableAmounts.PAO.add(
          Dinero({ amount: Math.round((val.act_price || 0) * 100) }).multiply(val.part_qty || 0)
        );
      } else if (!val.part_type) {
        //Do nothing for now.
      } else {
        const typeOfPart = val.part_type;

        const discMarkupAmount =
          val.prt_dsmk_m && val.prt_dsmk_m !== 0 && DiscountNotAlreadyCounted(val, job.joblines) // DO WE NEED TO COUNT PFP DISCOUNT HERE?
            ? val.prt_dsmk_m
              ? Dinero({ amount: Math.round(val.prt_dsmk_m * 100) })
              : Dinero({
                  amount: Math.round(val.act_price * 100)
                })
                  .multiply(val.part_qty || 0)
                  .percentage(Math.abs(val.prt_dsmk_p || 0))
                  .multiply(val.prt_dsmk_p > 0 ? 1 : -1)
            : Dinero();

        const partAmount = Dinero({
          amount: Math.round((val.act_price || 0) * 100)
        })
          .multiply(val.part_qty || 0)
          .add(discMarkupAmount);
        if (taxableAmounts[typeOfPart]) {
          taxableAmounts[typeOfPart] = taxableAmounts[typeOfPart].add(partAmount);
        } else {
          const isTaxableCustomType =
            IsTrueOrYes(pfp?.[typeOfPart]?.prt_tax_in) || pfp?.[typeOfPart]?.prt_tax_in === true;

          if (isTaxableCustomType) {
            if (!taxableAmounts[typeOfPart]) taxableAmounts[typeOfPart] = Dinero();
            taxableAmounts[typeOfPart] = taxableAmounts[typeOfPart].add(partAmount);
          }
        }
      }
    });

  //Check in the PFL file which types of labor are taxable. Add the amount that is considered taxable to the taxable amounts total.
  Object.keys(taxableAmounts)
    .filter((key) => key.startsWith("LA"))
    .map((key) => {
      const isLaborTypeTaxable = job.cieca_pfl[key]?.lbr_tax_in;
      if (isLaborTypeTaxable) {
        taxableAmounts[key] = taxableAmounts[key].add(otherTotals.rates[key.toLowerCase()].total);
      }
    });

  Object.keys(taxableAmounts)
    .filter((key) => key.startsWith("MA"))
    .map((key) => {
      const isTypeTaxable = job.materials[key]?.tax_ind;
      if (isTypeTaxable) {
        taxableAmounts[key] = taxableAmounts[key].add(otherTotals.rates[key.toLowerCase()].total);
      }
    });
  //Add towing and storage taxable amounts
  const stlTowing = job.cieca_stl?.data.find((c) => c.ttl_typecd === "OTTW" || c.ttl_type === "OTTW");
  const stlStorage = job.cieca_stl?.data.find((c) => c.ttl_typecd === "OTST" || c.ttl_type === "OTST");

  if (stlTowing)
    taxableAmounts.TOW = taxableAmounts.TOW.add(
      Dinero({
        amount: Math.round(stlTowing.t_amt * 100)
      })
    );
  if (!stlTowing && !job.ciecaid && job.towing_payable)
    taxableAmounts.TOW = taxableAmounts.TOW.add(
      Dinero({
        amount: Math.round((job.towing_payable || 0) * 100)
      })
    );

  if (stlStorage) {
    taxableAmounts.STOR = taxableAmounts.STOR.add(
      Dinero({
        amount: Math.round(stlStorage.t_amt * 100)
      })
    );
  }

  if (!stlStorage && !job.ciecaid && job.storage_payable)
    taxableAmounts.STOR = taxableAmounts.STOR.add(
      Dinero({
        amount: Math.round((job.storage_payable || 0) * 100)
      })
    );

  //For any profile level markups/discounts, add them in now as well.
  Object.keys(otherTotals.parts.adjustments).forEach((key) => {
    const adjustmentAmount = otherTotals.parts.adjustments[key];
    if (adjustmentAmount.getAmount() !== 0 && pfp[key]?.prt_tax_in) {
      if (taxableAmounts[key]) {
        taxableAmounts[key] = taxableAmounts[key].add(adjustmentAmount);
      } else {
        taxableAmounts[key] = Dinero().add(adjustmentAmount);
      }
    }
  });

  taxableAmounts.total = Object.values(taxableAmounts).reduce((acc, amount) => acc.add(amount), Dinero({ amount: 0 }));

  // console.log("*** Taxable Amounts***");
  // console.table(JSON.parse(JSON.stringify(taxableAmounts)));

  //For the taxable amounts, figure out which tax type applies.
  //Then sum up the total of that tax type and then calculate the thresholds.

  const taxableAmountsByTier = {
    ty1Tax: Dinero(),
    ty2Tax: Dinero(),
    ty3Tax: Dinero(),
    ty4Tax: Dinero(),
    ty5Tax: Dinero(),
    ty6Tax: Dinero()
  };
  const totalTaxByTier = {
    ty1Tax: Dinero(),
    ty2Tax: Dinero(),
    ty3Tax: Dinero(),
    ty4Tax: Dinero(),
    ty5Tax: Dinero(),
    ty6Tax: Dinero()
  };

  const pfl = job.cieca_pfl;
  const pfm = job.materials;
  const pfo = job.cieca_pfo;
  Object.keys(taxableAmounts).map((key) => {
    try {
      if (key.startsWith("PA") && key !== "PAE") {
        const typeOfPart = key; // === "PAM" ? "PAC" : key;
        //At least one of these scenarios must be taxable.
        for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
          if (IsTrueOrYes(pfp[typeOfPart][`prt_tx_in${tyCounter}`])) {
            //This amount is taxable for this type.
            taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
              taxableAmounts[typeOfPart]
            );
          }
        }
      } else if (key.startsWith("MA")) {
        //Materials Handling
        for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
          if (IsTrueOrYes(pfm[key][`mat_tx_in${tyCounter}`])) {
            //This amount is taxable for this type.
            taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
              taxableAmounts[key]
            );
          }
        }
      } else if (key.startsWith("LA")) {
        //Labor.
        for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
          if (key === "LA1" || key === "LA2" || key === "LA3" || key === "LA4") {
            if (IsTrueOrYes(pfl["LAU"][`lbr_tx_in${tyCounter}`])) {
              //This amount is taxable for this type.
              taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
                taxableAmounts[key]
              );
            }
          } else if (key === "LAA" && !pfl[key]) {
            if (IsTrueOrYes(pfl["LAB"][`lbr_tx_in${tyCounter}`])) {
              //This amount is taxable for this type.
              taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
                taxableAmounts[key]
              );
            }
          } else {
            if (IsTrueOrYes(pfl[key][`lbr_tx_in${tyCounter}`])) {
              //This amount is taxable for this type.
              taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
                taxableAmounts[key]
              );
            }
          }
        }
      } else if (key === "TOW") {
        for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
          if (IsTrueOrYes(pfo[`tow_t_in${tyCounter}`])) {
            //This amount is taxable for this type.
            taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
              taxableAmounts[key]
            );
          }
        }
      } else if (key === "STOR") {
        for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
          if (IsTrueOrYes(pfo[`stor_t_in${tyCounter}`])) {
            //This amount is taxable for this type.
            taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
              taxableAmounts[key]
            );
          }
        }
      } else if (pfp[key]) {
        //Custom part types (e.g. CC*) should flow through taxableAmountsByTier too.
        let assignedToTier = false;
        for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
          if (IsTrueOrYes(pfp[key][`prt_tx_in${tyCounter}`])) {
            taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
              taxableAmounts[key]
            );
            assignedToTier = true;
          }
        }

        if (!assignedToTier && (IsTrueOrYes(pfp[key].prt_tax_in) || pfp[key].prt_tax_in === true)) {
          taxableAmountsByTier.ty1Tax = taxableAmountsByTier.ty1Tax.add(taxableAmounts[key]);
        }
      }
    } catch (error) {
      logger.log("job-totals-USA Key with issue", "warn", null, job.id, {
        key: key,
        error: error.message,
        stack: error.stack
      });
    }
  });

  if (job.adjustment_bottom_line && job.adjustment_bottom_line !== 0) {
    for (let tyCounter = 1; tyCounter <= 5; tyCounter++) {
      if (IsTrueOrYes(pfp["PAN"][`prt_tx_in${tyCounter}`])) {
        //This amount is taxable for this type.
        taxableAmountsByTier[`ty${tyCounter}Tax`] = taxableAmountsByTier[`ty${tyCounter}Tax`].add(
          Dinero({
            amount: Math.round(job.adjustment_bottom_line * 100)
          })
        );
      }
    }
  }

  const remainingTaxableAmounts = taxableAmountsByTier;
  // console.log("*** Taxable Amounts by Tier***");
  // console.table(JSON.parse(JSON.stringify(taxableAmountsByTier)));

  Object.keys(taxableAmountsByTier).forEach((taxTierKey) => {
    try {
      let tyCounter = taxTierKey[2]; //Get the number from the key.
      //i represents the tax number. If we got here, this type of tax is applicable. Now we need to add based on the thresholds.
      for (let threshCounter = 1; threshCounter <= 5; threshCounter++) {
        const thresholdAmount = parseFloat(job.cieca_pft[`ty${tyCounter}_thres${threshCounter}`]) || 0;
        const thresholdTaxRate = parseFloat(job.cieca_pft[`ty${tyCounter}_rate${threshCounter}`]) || 0;
        // console.log(taxTierKey, tyCounter, threshCounter, thresholdAmount, thresholdTaxRate);
        let taxableAmountInThisThreshold;
        if (
          thresholdAmount === 9999.99 ||
          InstanceMgr({
            imex: false,
            rome: thresholdAmount === 0 && parseInt(tyCounter) === 1
          })
        ) {
          //
          // THis is the last threshold. Tax the entire remaining amount.
          taxableAmountInThisThreshold = remainingTaxableAmounts[taxTierKey];
          remainingTaxableAmounts[taxTierKey] = Dinero();
        } else {
          if (thresholdAmount >= remainingTaxableAmounts[taxTierKey].getAmount() / 100) {
            //This threshold is bigger than the remaining taxable balance. Add it all.
            taxableAmountInThisThreshold = remainingTaxableAmounts[taxTierKey];
            remainingTaxableAmounts[taxTierKey] = Dinero();
          } else {
            //Take the size of the threshold from the remaining amount, tax it, and do it all over.
            taxableAmountInThisThreshold = Dinero({
              amount: Math.round(thresholdAmount * 100)
            });
            remainingTaxableAmounts[taxTierKey] =
              remainingTaxableAmounts[taxTierKey].subtract(taxableAmountInThisThreshold);
          }
        }

        const taxAmountToAdd = taxableAmountInThisThreshold.percentage(thresholdTaxRate);

        totalTaxByTier[taxTierKey] = totalTaxByTier[taxTierKey].add(taxAmountToAdd);
      }
    } catch (error) {
      logger.log("job-totals-USA - PFP Calculation Error", "error", null, job.id, {
        error: error.message,
        stack: error.stack
      });
    }
  });

  // console.log("*** Total Tax by Tier Amounts***");
  // console.table(JSON.parse(JSON.stringify(totalTaxByTier)));

  stateTax = stateTax
    .add(totalTaxByTier.ty1Tax)
    .add(totalTaxByTier.ty2Tax)
    .add(totalTaxByTier.ty3Tax)
    .add(totalTaxByTier.ty4Tax)
    .add(totalTaxByTier.ty5Tax)
    .add(totalTaxByTier.ty6Tax);
  us_sales_tax_breakdown = totalTaxByTier;
  //console.log("Tiered Taxes Total for Parts/Labor", stateTax.toFormat());

  // This is not in use as such commented out.
  // let laborTaxTotal = Dinero();

  // if (Object.keys(job.cieca_pfl).length > 0) {
  //   //Ignore it now, we have calculated it above.
  //   //This was previously used for JCS before parts were also calculated at a different rate.
  // } else {
  //   //We don't have it, just add in how it was before.
  //   laborTaxTotal = otherTotals.rates.subtotal.percentage((job.tax_lbr_rt || 0) * 100); // THis is currently using the lbr tax rate from PFH not PFL.
  // }

  //console.log("Labor Tax Total", laborTaxTotal.toFormat());

  let ret = {
    subtotal: subtotal,
    taxableAmounts: taxableAmounts,
    federal_tax: subtotal
      .percentage((job.federal_tax_rate || 0) * 100)
      .add(otherTotals.additional.pvrt.percentage((job.federal_tax_rate || 0) * 100)),
    stateTax,
    us_sales_tax_breakdown,
    state_tax: stateTax,
    local_tax: subtotal.percentage((job.local_tax_rate || 0) * 100)
  };
  ret.total_repairs = ret.subtotal
    .add(ret.federal_tax)
    .add(ret.state_tax)
    .add(ret.local_tax)
    .add(otherTotals.additional.pvrt);

  ret.custPayable = {
    deductible: Dinero({ amount: Math.round((job.ded_amt || 0) * 100) }) || 0,
    federal_tax: job.ca_gst_registrant
      ? job.ca_customer_gst === 0 || job.ca_customer_gst === null
        ? ret.federal_tax
        : Dinero({ amount: Math.round(job.ca_customer_gst * 100) })
      : Dinero(),
    other_customer_amount: Dinero({
      amount: Math.round((job.other_amount_payable || 0) * 100)
    }),
    dep_taxes: Dinero({
      amount: Math.round((job.depreciation_taxes || 0) * 100)
    })
  };

  ret.custPayable.total = ret.custPayable.deductible
    .add(ret.custPayable.federal_tax)
    .add(ret.custPayable.other_customer_amount)
    .add(ret.custPayable.dep_taxes);

  ret.net_repairs = ret.total_repairs.subtract(ret.custPayable.total);

  return ret;
}

exports.default = Totals;

//eslint-disable-next-line no-unused-vars
function DiscountNotAlreadyCounted(jobline, joblines) {
  return false;
}

exports.DiscountNotAlreadyCounted = DiscountNotAlreadyCounted;

function ParseCalopCode(opcode) {
  if (!opcode) return [];
  return opcode.trim().split(" ");
}

exports.ParseCalopCode = ParseCalopCode;

function IsTrueOrYes(value) {
  return value === true || value === "Y" || value === "y";
}

// Function not in use from RO to IO Merger 02/05/2024
// async function UpdateJobLines(joblinesToUpdate) {
//   if (joblinesToUpdate.length === 0) return;
//   const updateQueries = joblinesToUpdate.map((line, index) =>
//     generateUpdateQuery(_.pick(line, ["id", "prt_dsmk_m", "prt_dsmk_p"]), index)
//   );
//   const query = `
//     mutation UPDATE_EST_LINES{
//       ${updateQueries}
//     }
//     `;
//   try {
//     const result = await adminClient.request(query);
//     void result;
//   } catch (error) {
//     logger.log("update-job-lines", "error", null, null, {
//       error: error.message,
//       stack: error.stack
//     });
//   }
// }

// const generateUpdateQuery = (lineToUpdate, index) => {
//   return `
//   update_joblines${index}: update_joblines(where: { id: { _eq: "${
//     lineToUpdate.id
//   }" } }, _set: ${JSON.stringify(lineToUpdate).replace(/"(\w+)"\s*:/g, "$1:")}) {
//     returning {
//       id
//     }
//   }`;
// };
