const logger = require("../../utils/logger");
const OAuthClient = require("intuit-oauth");
const client = require("../../graphql-client/graphql-client").client;
const queries = require("../../graphql-client/queries");
const { parse, stringify } = require("querystring");
const { InstanceEndpoints } = require("../../utils/instanceMgr");

const oauthClient = new OAuthClient({
  clientId: process.env.QBO_CLIENT_ID,
  clientSecret: process.env.QBO_SECRET,
  environment: process.env.NODE_ENV === "production" ? "production" : "sandbox",
  redirectUri: process.env.QBO_REDIRECT_URI
});

const url = InstanceEndpoints();

exports.default = async (req, res) => {
  const queryString = req.url.split("?").reverse()[0];
  const params = parse(queryString);
  try {
    logger.log("qbo-callback-create-token", "DEBUG", params.state, null, null);
    const authResponse = await oauthClient.createToken(req.url);
    if (authResponse.json.error) {
      logger.log("qbo-callback-error", "ERROR", params.state, null, {
        error: authResponse.json
      });
      res.redirect(`${url}/manage/accounting/qbo?error=${encodeURIComponent(JSON.stringify(authResponse.json))}`);
    } else {
      await client.request(queries.SET_QBO_AUTH_WITH_REALM, {
        email: params.state,
        qbo_auth: { ...authResponse.json, createdAt: Date.now() },
        qbo_realmId: params.realmId
      });
      logger.log("qbo-callback-create-token-success", "DEBUG", params.state, null, null);

      res.redirect(`${url}/manage/accounting/qbo?${stringify(params)}`);
    }
  } catch (e) {
    logger.log("qbo-callback-error", "ERROR", params.state, null, {
      error: e
    });
    res.status(400).json(e);
  }
};

exports.refresh = async (oauthClient, req) => {
  try {
    logger.log("qbo-token-refresh", "DEBUG", req.user.email, null, null);
    const authResponse = await oauthClient.refresh();
    await client.request(queries.SET_QBO_AUTH, {
      email: req.user.email,
      qbo_auth: { ...authResponse.json, createdAt: Date.now() }
    });
  } catch (error) {
    logger.log("qbo-token-refresh-error", "ERROR", req.user.email, null, {
      error
    });
  }
};
