"use strict";
Object.defineProperty(exports, "__esModule", {
    value: true
});
Object.defineProperty(exports, "MSupplyClient", {
    enumerable: true,
    get: function() {
        return MSupplyClient;
    }
});
const _config = /*#__PURE__*/ _interop_require_default(require("config"));
const _undici = require("undici");
const _logging = require("@tamanu/shared/services/logging");
const _fetchWithRetryBackoff = require("@tamanu/api-client/fetchWithRetryBackoff");
function _interop_require_default(obj) {
    return obj && obj.__esModule ? obj : {
        default: obj
    };
}
const GRAPHQL_ENDPOINT = '/graphql';
const AUTH_QUERY = `
  query Auth($password: String!, $username: String!) {
    authToken(password: $password, username: $username) {
      ... on AuthToken {
        __typename
        token
      }
      ... on AuthTokenError {
        __typename
        error {
          description
        }
      }
    }
  }
`;
let MSupplyClient = class MSupplyClient {
    async getSettings(facilityId) {
        const integrationSettings = await this.context.settings[facilityId]?.get('integrations.mSupplyMed');
        return integrationSettings ?? {};
    }
    async authenticate(facilityId) {
        const { host, backoff } = await this.getSettings(facilityId);
        const { username, password } = _config.default.integrations.mSupplyMed;
        const response = await (0, _fetchWithRetryBackoff.fetchWithRetryBackoff)(`${host}${GRAPHQL_ENDPOINT}`, {
            fetch: _undici.fetch,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                query: AUTH_QUERY,
                variables: {
                    username,
                    password
                }
            })
        }, {
            ...backoff,
            log: _logging.log
        });
        const { data } = await response.json();
        const token = data?.authToken?.token;
        if (!token) {
            throw new Error('mSupply authentication failed: no token returned');
        }
        return token;
    }
    async graphqlQuery({ host, query, variables, authToken, backoff }) {
        const response = await (0, _fetchWithRetryBackoff.fetchWithRetryBackoff)(`${host}${GRAPHQL_ENDPOINT}`, {
            fetch: _undici.fetch,
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                Authorization: `Bearer ${authToken}`
            },
            body: JSON.stringify({
                query,
                ...variables && {
                    variables
                }
            })
        }, {
            ...backoff,
            log: _logging.log
        });
        return response.json();
    }
    constructor(context){
        this.context = context;
    }
};

//# sourceMappingURL=MSupplyClient.js.map