import { V3TargetFinder, SgiGroupsV12026April } from "../ipc/ipc-estimate-utils";
import { store } from "../redux/store";
import { WhichMPIRulesetToApply } from "./constants";

export default function GetJobTarget({ group, v_age, targets, close_date, v_mileage, job }) {
  const ins_rule_set = store.getState().user?.bodyshop?.ins_rule_set;

  switch (ins_rule_set) {
    case "SGI":
      let type = job.v_type === "PC" || job.v_type === "SUV" ? "PC" : job.v_type;
      const sgiTarget = SgiGroupsV12026April.find((f) => f.make === job.v_makedesc.toUpperCase()
        && (f.type === type || f.type === null)
        && job.v_age >= f.ageGte
        && (f.ageLt === null ? true : job.v_age < f.ageLt)
      );
      //Check if this is an RCC job. 
      if (job.sgi_rcc) {
        return 0;
      }
      if (v_mileage && v_mileage <= 20000) {
        return 0;
      }
      return sgiTarget?.target || 0;

    case "MPI":
    default:
      const newTargets = store.getState().user.targets;

      const rulesToApply = WhichMPIRulesetToApply(close_date);
      if (rulesToApply === "V3") {
        //V3 Check - If vehicle is less than 20,000KM, there is NO TARGET.
        if (v_mileage && v_mileage <= 20000) {
          return 0;
        }
        const v3Target = V3TargetFinder(job);
        return v3Target;
      } else {
        const newTargetsForGroup = newTargets.filter((t) => t.name === rulesToApply && t.group === group);

        if (!newTargetsForGroup) return 0;
        const newTargetPc = newTargetsForGroup.filter((t) => t.ageGte <= v_age && (t.ageLt ? t.ageLt > v_age : true));

        if (newTargetPc.length === 0) return 1;
        else if (newTargetPc.length === 1) return newTargetPc[0].target;
        else {
          return 1;
        }
      }

  }
}
