const { SecretsManagerClient, GetSecretValueCommand } = require("@aws-sdk/client-secrets-manager");
const { InstanceRegion } = require("../../utils/instanceMgr");

const client = new SecretsManagerClient({
  region: InstanceRegion()
});

/**
 * @description Get shop credentials from AWS Secrets Manager
 * @param bodyshop
 * @returns {Promise<{error}|{merchantkey: *, apikey: *}|any>}
 */
const getShopCredentials = async (bodyshop) => {
  // In Dev/Testing we will use the environment variables
  if (process.env?.NODE_ENV !== "production") {
    return {
      merchantkey: process.env.INTELLIPAY_MERCHANTKEY,
      apikey: process.env.INTELLIPAY_APIKEY
    };
  }

  // In Production, we will use the AWS Secrets Manager
  if (bodyshop?.imexshopid) {
    try {
      const secret = await client.send(
        new GetSecretValueCommand({
          SecretId: `intellipay-credentials-${bodyshop.imexshopid}`,
          VersionStage: "AWSCURRENT" // VersionStage defaults to AWSCURRENT if unspecified
        })
      );
      return JSON.parse(secret.SecretString);
    } catch (error) {
      return {
        error: error.message
      };
    }
  }
};

module.exports = getShopCredentials;
