const DEFAULT_COMPANY_ID = process.env.CHATTER_DEFAULT_COMPANY_ID;
const client = require("../graphql-client/graphql-client").client;
const { createChatterClient } = require("./chatter-client");
const InstanceManager = require("../utils/instanceMgr").default;

const GET_BODYSHOP_FOR_CHATTER = `
  query GET_BODYSHOP_FOR_CHATTER($id: uuid!) {
    bodyshops_by_pk(id: $id) {
      id
      shopname
      address1
      city
      state
      zip_post
      imexshopid
      chatterid
      chatter_company_id
    }
  }
`;

const UPDATE_BODYSHOP_CHATTER_FIELDS = `
  mutation UPDATE_BODYSHOP_CHATTER_FIELDS($id: uuid!, $chatter_company_id: String!, $chatterid: String!) {
    update_bodyshops_by_pk(pk_columns: {id: $id}, _set: {chatter_company_id: $chatter_company_id, chatterid: $chatterid}) {
      id
      chatter_company_id
      chatterid
    }
  }
`;

const createLocation = async (req, res) => {
  const { logger } = req;
  const { bodyshopID, googlePlaceID } = req.body;

  if (!DEFAULT_COMPANY_ID) {
    logger.log("chatter-create-location-no-default-company", "warn", null, null, { bodyshopID });
    return res.json({ success: false, message: "No default company set" });
  }

  if (!googlePlaceID) {
    logger.log("chatter-create-location-no-google-place-id", "warn", null, null, { bodyshopID });
    return res.json({ success: false, message: "No google place id provided" });
  }

  if (!bodyshopID) {
    logger.log("chatter-create-location-invalid-bodyshop", "warn", null, null, { bodyshopID });
    return res.json({ success: false, message: "No bodyshop id" });
  }

  try {
    const { bodyshops_by_pk: bodyshop } = await client.request(GET_BODYSHOP_FOR_CHATTER, { id: bodyshopID });

    if (!bodyshop) {
      logger.log("chatter-create-location-bodyshop-not-found", "warn", null, null, { bodyshopID });
      return res.json({ success: false, message: "Bodyshop not found" });
    }

    if (bodyshop.chatter_company_id && bodyshop.chatterid) {
      logger.log("chatter-create-location-already-exists", "warn", null, null, {
        bodyshopID
      });
      return res.json({ success: false, message: "This Bodyshop already has a location associated with it" });
    }

    const chatterApi = await createChatterClient(DEFAULT_COMPANY_ID);

    const locationIdentifier = bodyshop?.imexshopid ?? `${DEFAULT_COMPANY_ID}-${bodyshop.id}`;

    const locationPayload = {
      name: bodyshop.shopname,
      locationIdentifier: locationIdentifier,
      address: bodyshop.address1,
      postalCode: bodyshop.zip_post,
      state: bodyshop.state,
      city: bodyshop.city,
      country: InstanceManager({ imex: "Canada", rome: "US" }),
      googlePlaceId: googlePlaceID,
      status: "active"
    };

    logger.log("chatter-create-location-calling-api", "info", null, null, { bodyshopID, locationIdentifier });

    const response = await chatterApi.createLocation(DEFAULT_COMPANY_ID, locationPayload);

    if (!response.location?.id) {
      logger.log("chatter-create-location-no-location-id", "error", null, null, { bodyshopID, response });
      return res.json({ success: false, message: "No location ID in response", data: response });
    }

    await client.request(UPDATE_BODYSHOP_CHATTER_FIELDS, {
      id: bodyshopID,
      chatter_company_id: DEFAULT_COMPANY_ID,
      chatterid: String(response.location.id)
    });

    logger.log("chatter-create-location-success", "info", null, null, {
      bodyshopID,
      chatter_company_id: DEFAULT_COMPANY_ID,
      chatterid: response.location.id,
      locationIdentifier
    });

    return res.json({ success: true, data: response });
  } catch (error) {
    logger.log("chatter-create-location-error", "error", null, null, {
      bodyshopID,
      error: error.message,
      status: error.status,
      data: error.data
    });

    return res.json({
      success: false,
      message: error.message || "Failed to create location",
      error: error.data
    });
  }
};

module.exports = createLocation;
