"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.validatePayloadAndCreateClient = void 0;
const extensions_core_1 = require("@awell-health/extensions-core");
const lodash_1 = require("lodash");
const zod_1 = __importDefault(require("zod"));
const client_1 = require("../api/client");
const constants_1 = require("../api/constants");
const settings_1 = require("../settings");
const validatePayloadAndCreateClient = async ({ fieldsSchema, payload, }) => {
    const { settings: { salesforceSubdomain, clientId, clientSecret, username, password, apiVersion, }, pathway: { id: pathwayId }, activity: { id: activityId }, fields, settings, } = (0, extensions_core_1.validate)({
        schema: zod_1.default.object({
            fields: fieldsSchema,
            settings: settings_1.SettingsValidationSchema,
            pathway: zod_1.default.object({ id: zod_1.default.string() }),
            activity: zod_1.default.object({ id: zod_1.default.string() }),
        }),
        payload,
    });
    const getGrantType = () => {
        if ((0, lodash_1.isEmpty)(username) || (0, lodash_1.isEmpty)(password))
            return 'client_credentials';
        return 'password';
    };
    const grantType = getGrantType();
    const getRequestConfig = () => {
        if (grantType === 'client_credentials')
            return {
                client_id: clientId,
                client_secret: clientSecret,
            };
        if (!(0, lodash_1.isEmpty)(username) && !(0, lodash_1.isEmpty)(password)) {
            return {
                client_id: clientId,
                client_secret: clientSecret,
                username: username,
                password: password,
            };
        }
        throw new Error('Should not happen');
    };
    const salesforceClient = new client_1.SalesforceRestAPIClient({
        authUrl: (0, constants_1.getAuthUrl)('REST', grantType, salesforceSubdomain),
        baseUrl: (0, constants_1.getApiUrl)('REST', salesforceSubdomain),
        requestConfig: getRequestConfig(),
        apiVersion: apiVersion !== null && apiVersion !== void 0 ? apiVersion : constants_1.DEFAULT_API_VERSION,
    });
    return { salesforceClient, fields, settings, pathwayId, activityId };
};
exports.validatePayloadAndCreateClient = validatePayloadAndCreateClient;
//# sourceMappingURL=validatePayloadAndCreateClient.js.map