const client = require("../graphql-client/graphql-client").client;
const { UPDATE_JOB_BY_ID } = require("../integrations/partsManagement/partsManagement.queries");

/**
 * PATCH handler to update job status (parts management only)
 * @param req
 * @param res
 * @returns {Promise<void>}
 */
module.exports = async (req, res) => {
  const { id } = req.params;
  const { status } = req.body;
  if (!status) {
    return res.status(400).json({ error: "Missing required field: status" });
  }
  try {
    // Fetch job to get shopid
    const jobResp = await client.request(`query GetJob($id: uuid!) { jobs_by_pk(id: $id) { id shopid } }`, { id });
    const job = jobResp.jobs_by_pk;
    if (!job) {
      return res.status(404).json({ error: "Job not found" });
    }
    // Fetch bodyshop to check external_shop_id
    const shopResp = await client.request(
      `query GetBodyshop($id: uuid!) { bodyshops_by_pk(id: $id) { id external_shop_id } }`,
      { id: job.shopid }
    );
    if (!shopResp.bodyshops_by_pk || !shopResp.bodyshops_by_pk.external_shop_id) {
      return res.status(400).json({ error: "Cannot patch: parent bodyshop does not have an external_shop_id." });
    }
    // Update job status
    const updateResp = await client.request(UPDATE_JOB_BY_ID, { id, job: { status } });
    if (!updateResp.update_jobs_by_pk) {
      return res.status(404).json({ error: "Job not found after update" });
    }
    return res.json(updateResp.update_jobs_by_pk);
  } catch (err) {
    return res.status(500).json({ error: "Failed to update job status.", detail: err });
  }
};
