import Axios from "axios";
import _ from "lodash";
import { logImEXEvent } from "../../firebase/firebase.utils";
import { INSERT_NEW_JOB, QUERY_JOB_FOR_DUPE } from "../../graphql/jobs.queries";
import dayjs from "../../utils/day";
import i18n from "i18next";

export default async function DuplicateJob({
  apolloClient,
  jobId,
  config,
  completionCallback,
  keepJobLines = false,
  currentUser
}) {
  logImEXEvent("job_duplicate");

  const { defaultOpenStatus, timezone } = config;
  //get a list of all fields on the job
  const res = await apolloClient.query({
    query: QUERY_JOB_FOR_DUPE,
    variables: { id: jobId }
  });

  const { jobs_by_pk } = res.data;
  const existingJob = _.cloneDeep(jobs_by_pk);
  delete existingJob.__typename;
  delete existingJob.id;
  delete existingJob.created_user_email;
  delete existingJob.createdat;
  delete existingJob.updatedat;
  delete existingJob.cieca_stl;
  delete existingJob.cieca_ttl;
  !keepJobLines && delete existingJob.clm_total;

  const newJob = {
    ...existingJob,
    date_estimated: dayjs().tz(timezone, false).format("YYYY-MM-DD"),
    date_open: dayjs(),
    status: defaultOpenStatus
  };

  if (currentUser?.email) {
    newJob.created_user_email = currentUser.email;
  }

  const _tempLines = _.cloneDeep(existingJob.joblines);
  _tempLines.forEach((line) => {
    delete line.id;
    delete line.__typename;
    line.manual_line = true;
  });
  newJob.joblines = keepJobLines ? _tempLines : [];

  delete newJob.joblines;
  newJob.joblines = keepJobLines ? { data: _tempLines } : null;

  const res2 = await apolloClient.mutate({
    mutation: INSERT_NEW_JOB,
    variables: { job: [newJob] }
  });
  await Axios.post("/job/totalsssu", {
    id: res2.data.insert_jobs.returning[0].id
  });

  if (completionCallback) completionCallback(res2.data.insert_jobs.returning[0].id);

  //insert the new job. call the callback with the returned ID when done.

  return;
}

export async function CreateIouForJob({ apolloClient, jobId, config, jobLinesToKeep, currentUser }) {
  logImEXEvent("job_create_iou");

  const { status, timezone } = config;
  //get a list of all fields on the job
  const res = await apolloClient.query({
    query: QUERY_JOB_FOR_DUPE,
    variables: { id: jobId }
  });

  const { jobs_by_pk } = res.data;
  const existingJob = _.cloneDeep(jobs_by_pk);
  delete existingJob.__typename;
  delete existingJob.id;
  delete existingJob.createdat;
  delete existingJob.updatedat;
  delete existingJob.cieca_stl;
  delete existingJob.cieca_ttl;

  const newJob = {
    ...existingJob,
    converted: true,
    status: status,
    iouparent: jobId,
    date_estimated: dayjs().tz(timezone, false).format("YYYY-MM-DD"),
    date_open: dayjs(),
    audit_trails: {
      data: [
        {
          useremail: config.useremail,
          bodyshopid: config.bodyshopid,
          operation: i18n.t("audit_trail.messages.jobioucreated")
        }
      ]
    }
  };

  const selectedJoblinesIds = jobLinesToKeep.map((l) => l.id);

  const _tempLines = _.cloneDeep(existingJob.joblines).filter((l) => selectedJoblinesIds.includes(l.id));
  _tempLines.forEach((line) => {
    delete line.id;
    delete line.__typename;
    line.oem_partno = `${line.oem_partno ? `${line.oem_partno} - ` : ``}IOU $${
      (line.act_price && line.act_price.toFixed(2)) || 0
    }/${line.mod_lb_hrs || 0}hrs`;
    line.act_price = 0;
    line.mod_lb_hrs = 0;
    line.manual_line = true;
  });

  delete newJob.joblines;
  newJob.joblines = { data: _tempLines };

  if (currentUser?.email) {
    newJob.created_user_email = currentUser.email;
  }
  const res2 = await apolloClient.mutate({
    mutation: INSERT_NEW_JOB,
    variables: { job: [newJob] }
  });

  Axios.post("/job/totalsssu", {
    id: res2.data.insert_jobs.returning[0].id
  });

  //insert the new job. call the callback with the returned ID when done.

  return res2.data.insert_jobs.returning[0].id;
}
