"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __generator = (this && this.__generator) || function (thisArg, body) {
    var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
    return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
    function verb(n) { return function (v) { return step([n, v]); }; }
    function step(op) {
        if (f) throw new TypeError("Generator is already executing.");
        while (g && (g = 0, op[0] && (_ = 0)), _) try {
            if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
            if (y = 0, t) op = [op[0] & 2, t.value];
            switch (op[0]) {
                case 0: case 1: t = op; break;
                case 4: _.label++; return { value: op[1], done: false };
                case 5: _.label++; y = op[1]; op = [0]; continue;
                case 7: op = _.ops.pop(); _.trys.pop(); continue;
                default:
                    if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
                    if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
                    if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
                    if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
                    if (t[2]) _.ops.pop();
                    _.trys.pop(); continue;
            }
            op = body.call(thisArg, _);
        } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
        if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
    }
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.SEND_OTP_MAIL_ROUTE = exports.OTP_CREATE_TOKEN_ROUTE = exports.RESEND_CONFIRMATION_EMAIL_ROUTE = exports.UNWIND_ROUTE = exports.IMPERSONATE_BY_TEAM_ROUTE = exports.IMPERSONATE_ROUTE = exports.SWITCH_ROUTE = exports.LOGOUT_ROUTE = exports.GET_USER_ROUTE = exports.CREATE_TOKEN_ONE_TIME_CODE_ROUTE = exports.CREATE_TOKEN_ROUTE = void 0;
var lodash_1 = require("lodash");
var sha1_1 = __importDefault(require("sha1"));
var BringgDashboardSDK_1 = require("../../BringgDashboardSDK");
var BringgException_1 = require("../../Core/BringgException");
var ExceptionReason_1 = require("../../Core/ExceptionReason");
var Enums_1 = require("../../Core/Http/Enums");
var URLEndpoint_1 = __importDefault(require("../../Core/Http/URLEndpoint"));
var Route_1 = require("../Route");
var ServiceRequest_1 = require("../ServiceRequest");
var User_1 = __importDefault(require("./User"));
exports.CREATE_TOKEN_ROUTE = new Route_1.Route('/tokens', 1 /* HttpMethod.POST */);
exports.CREATE_TOKEN_ONE_TIME_CODE_ROUTE = new Route_1.Route('/tokens/one_time', 1 /* HttpMethod.POST */);
exports.GET_USER_ROUTE = new Route_1.Route('/tokens', 0 /* HttpMethod.GET */);
exports.LOGOUT_ROUTE = new Route_1.Route('/tokens', 4 /* HttpMethod.DELETE */);
exports.SWITCH_ROUTE = new Route_1.Route('/tokens/switch_accounts', 1 /* HttpMethod.POST */);
exports.IMPERSONATE_ROUTE = new Route_1.Route('/tokens/impersonate', 1 /* HttpMethod.POST */);
exports.IMPERSONATE_BY_TEAM_ROUTE = new Route_1.Route('/support/impersonate', 1 /* HttpMethod.POST */);
exports.UNWIND_ROUTE = new Route_1.Route('/tokens/unwind_impersonate', 1 /* HttpMethod.POST */);
exports.RESEND_CONFIRMATION_EMAIL_ROUTE = new Route_1.Route('/tokens/resend_confirmation_email', 1 /* HttpMethod.POST */);
exports.OTP_CREATE_TOKEN_ROUTE = new Route_1.Route('/otp', 1 /* HttpMethod.POST */);
exports.SEND_OTP_MAIL_ROUTE = new Route_1.Route('/otp/send', 1 /* HttpMethod.POST */);
var AuthService = /** @class */ (function () {
    function AuthService(clientId, endpoint) {
        this.clientId = clientId;
        this.endpoint = endpoint;
    }
    AuthService.init = function (region) {
        var configurationProvider = (0, BringgDashboardSDK_1.getConfigurationProvider)();
        return new AuthService(configurationProvider.getClientId(), region
            ? URLEndpoint_1.default.parse(configurationProvider.getAuthenticationEndpoint(region))
            : URLEndpoint_1.default.parse(configurationProvider.getRegionDiscoveryEndpoint()));
    };
    AuthService.isRecaptchaNeeded = function (object) {
        return 'recaptcha_stoken' in object;
    };
    AuthService.isRegionInformationNeeded = function (object) {
        return 'merchants_data' in object;
    };
    AuthService.prototype.loginWithOneTimeCode = function (token, secret) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.CREATE_TOKEN_ONE_TIME_CODE_ROUTE, {}, undefined, {
                            token: token,
                            secret: secret
                        })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status === Enums_1.HttpStatusCode.UNAUTHORIZED) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), 'Invalid one-time code.');
                            }
                            if (status === Enums_1.HttpStatusCode.OK) {
                                return new User_1.default(data);
                            }
                            //unknown failure
                            (0, ServiceRequest_1.logErrorResponse)(response);
                            throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), response.statusText);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.loginWithSessionCode = function (code, session) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.CREATE_TOKEN_ROUTE, {}, undefined, {
                            code: code,
                            session: session
                        })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status === Enums_1.HttpStatusCode.UNAUTHORIZED) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), 'Invalid session or code');
                            }
                            if (status === Enums_1.HttpStatusCode.OK) {
                                return new User_1.default(data);
                            }
                            //unknown failure
                            (0, ServiceRequest_1.logErrorResponse)(response);
                            throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), response.statusText);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.loginWithEmail = function (email, password, merchant_uuid, recaptcha, recaptcha_qa_token) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.CREATE_TOKEN_ROUTE, {}, undefined, {
                            email: (0, sha1_1.default)((0, lodash_1.toLower)(email)).toString(),
                            password: password,
                            merchant_uuid: merchant_uuid,
                            remember_me: true,
                            recaptcha: recaptcha,
                            recaptcha_qa_token: recaptcha_qa_token
                        })
                            .handle(function (response) {
                            var message = response.message;
                            var _a = response, data = _a.data, status = _a.status;
                            if ((0, lodash_1.isUndefined)(status) ||
                                status === Enums_1.HttpStatusCode.NOT_FOUND ||
                                status === Enums_1.HttpStatusCode.INTERNAL_SERVER_ERROR) {
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), Enums_1.REGION_NOT_WORKING, new Error(message));
                            }
                            //well known errors
                            if (status === Enums_1.HttpStatusCode.UNAUTHORIZED) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                if (data.resend_confirmation_available) {
                                    throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), 'User is blocked', null, data);
                                }
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), 'Invalid user name or password', null, data);
                            }
                            //recaptcha
                            if (status === Enums_1.HttpStatusCode.LOCKED || AuthService.isRecaptchaNeeded(data)) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.LOCKED), 'Recaptcha validation needed', null, data.recaptcha_stoken);
                            }
                            //multiple merchants
                            if (status === Enums_1.HttpStatusCode.FAILED_DEPENDENCY || AuthService.isRegionInformationNeeded(data)) {
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.FAILED_DEPENDENCY), 'Merchant and region information needed', null, data.merchants_data);
                            }
                            // 2FA required
                            if (status === Enums_1.HttpStatusCode.OK && data.otp_sent) {
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.OTP_REQUIRED, 'Two-factor Authentication is required. Please provide one time code', null, { expiration: data.expiration });
                            }
                            //success
                            if (status === Enums_1.HttpStatusCode.OK) {
                                return new User_1.default(data);
                            }
                            //unknown failure
                            (0, ServiceRequest_1.logErrorResponse)(response);
                            throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), response.statusText);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.loginWithToken = function (authToken) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.GET_USER_ROUTE, null, { auth_token: authToken })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), status === Enums_1.HttpStatusCode.FORBIDDEN || status === Enums_1.HttpStatusCode.UNAUTHORIZED
                                    ? 'Unauthorized'
                                    : 'Temporary unavailable');
                            }
                            return new User_1.default(data);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.logout = function (authToken) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.LOGOUT_ROUTE, null, { auth_token: authToken })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK || !data.success) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.BAD_REQUEST), 'Unable to logout');
                            }
                            return data.success;
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.switchAccounts = function (authToken) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.SWITCH_ROUTE, null, { auth_token: authToken })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK || !data.success) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.BAD_REQUEST), 'Unable to switch accounts');
                            }
                            return new User_1.default(data.user);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.unwind = function (authToken) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.UNWIND_ROUTE, null, { auth_token: authToken })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK || data.success === false) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.BAD_REQUEST), status !== Enums_1.HttpStatusCode.OK ? 'Unable to return to original user' : 'Not in impersonation mode');
                            }
                            return new User_1.default(data);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.impersonate = function (authToken, user_id) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.IMPERSONATE_ROUTE, null, { auth_token: authToken, user_id: user_id })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK || data.success === false) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.BAD_REQUEST), 'Unable to impersonate requested account');
                            }
                            data.enable_logs = true;
                            data.beta = true;
                            data.debug = true;
                            return new User_1.default(data);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.impersonateByTeam = function (authToken, team_id) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.IMPERSONATE_BY_TEAM_ROUTE, null, { team_id: team_id }, { auth_token: authToken })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK || !data.success) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.BAD_REQUEST), 'Unable to impersonate requested team');
                            }
                            return new User_1.default(data.user);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.resendConfirmationEmail = function (email, password, merchant_uuid, recaptcha, recaptcha_qa_token) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.RESEND_CONFIRMATION_EMAIL_ROUTE, null, null, {
                            email: (0, sha1_1.default)((0, lodash_1.toLower)(email)).toString(),
                            password: password,
                            merchant_uuid: merchant_uuid,
                            recaptcha: recaptcha,
                            recaptcha_qa_token: recaptcha_qa_token
                        })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status !== Enums_1.HttpStatusCode.OK || !data.success) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.BAD_REQUEST), 'Unable to resend confirmation email');
                            }
                            return true;
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.loginWithOTP = function (email, password, otp, merchant_uuid, recaptchaToken, recaptcha_qa_token, region) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.OTP_CREATE_TOKEN_ROUTE, null, null, {
                            email: (0, sha1_1.default)((0, lodash_1.toLower)(email)).toString(),
                            password: password,
                            merchant_uuid: merchant_uuid,
                            otp: otp,
                            region: region,
                            recaptchaToken: recaptchaToken,
                            recaptcha_qa_token: recaptcha_qa_token
                        })
                            .handle(function (response) {
                            var message = response.message;
                            var _a = response, data = _a.data, status = _a.status, statusText = _a.statusText;
                            //recaptcha
                            if (status === Enums_1.HttpStatusCode.LOCKED || AuthService.isRecaptchaNeeded(data)) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(Enums_1.HttpStatusCode.LOCKED), 'Recaptcha validation needed', null, data.recaptcha_stoken);
                            }
                            // handles wrong or expired OTP code
                            if (status === Enums_1.HttpStatusCode.UNAUTHORIZED) {
                                (0, ServiceRequest_1.logErrorResponse)(response);
                                throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), message, null, data);
                            }
                            if (status === Enums_1.HttpStatusCode.OK) {
                                return new User_1.default(data);
                            }
                            //unknown failure
                            (0, ServiceRequest_1.logErrorResponse)(response);
                            throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), statusText);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    AuthService.prototype.sendOtpEmail = function (email, protected_action) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                switch (_a.label) {
                    case 0: return [4 /*yield*/, new ServiceRequest_1.AnonymousServiceRequest(this.clientId)
                            .invoke(this.endpoint, exports.SEND_OTP_MAIL_ROUTE, null, null, {
                            email: (0, sha1_1.default)((0, lodash_1.toLower)(email)).toString(),
                            protected_action: protected_action
                        })
                            .handle(function (response) {
                            var data = response.data, status = response.status;
                            if (status === Enums_1.HttpStatusCode.OK) {
                                return data;
                            }
                            //unknown failure
                            (0, ServiceRequest_1.logErrorResponse)(response);
                            throw new BringgException_1.BringgException(ExceptionReason_1.ExceptionReason.fromHttpStatusCode(status), response.statusText);
                        })];
                    case 1: return [2 /*return*/, _a.sent()];
                }
            });
        });
    };
    return AuthService;
}());
exports.default = AuthService;
//# sourceMappingURL=AuthService.js.map