const logger = require("../utils/logger");
const queries = require("../graphql-client/queries");
const GraphQLClient = require("graphql-request").GraphQLClient;
const moment = require("moment-timezone");

exports.generatePpc = async (req, res) => {
  const { jobid } = req.body;
  const BearerToken = req.headers.authorization;
  logger.log("generate-ppc", "DEBUG", req.user.email, jobid, null);

  const client = new GraphQLClient(process.env.GRAPHQL_ENDPOINT, {
    headers: {
      Authorization: BearerToken
    }
  });
  try {
    const { jobs_by_pk: job } = await client
      .setHeaders({ Authorization: BearerToken })
      .request(queries.GET_JOB_FOR_PPC, {
        jobid: jobid
      });

    const ReturnVal = {
      ...job,
      trans_type: "P",
      create_dt: moment().tz(job.bodyshop.timezone).format("yyyyMMDD"),
      create_tm: moment().tz(job.bodyshop.timezone).format("HHmmSS"),
      incl_est: true,
      joblines: job.joblines.map((jl) => ({ ...jl, tran_code: 2 }))
    };

    res.json(ReturnVal);
  } catch (error) {
    res.status(400).json(error);
  }
};
