"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 });
var types_1 = require("@bringg/types");
var CrudService_1 = __importDefault(require("../../Core/CrudService"));
var User_consts_1 = require("../User.consts");
var UsersService = /** @class */ (function () {
    function UsersService(session) {
        this.service = new CrudService_1.default(session, 'users');
    }
    Object.defineProperty(UsersService.prototype, "session", {
        get: function () {
            return this.service.session;
        },
        enumerable: false,
        configurable: true
    });
    UsersService.prototype.delete = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.delete(userId)];
            });
        });
    };
    UsersService.prototype.deleteMany = function (userIds) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .delete(User_consts_1.ROUTES.DELETE_MANY)
                        .withPayload({ ids: userIds })
                        .withExtractor(function (response) { return response; })
                        .setException('Could not delete users')
                        .invoke()];
            });
        });
    };
    UsersService.prototype.closedTasks = function (userId, page) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.CLOSED_TASKS)
                        .withRouteParams({ userId: userId })
                        .withQueryString({ page: page })
                        .withExtractor(function (response) { return response; })
                        .setException("Could not get closed tasks for user ".concat(userId))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.assignedTasksCount = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.TOTAL_TASKS)
                        .withRouteParams({ userId: userId })
                        .withExtractor(function (response) { return response.count; })
                        .setException("Could not get assigned tasks count for user ".concat(userId))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.create = function (user) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.create(user).then(function (response) { return response.user; })];
            });
        });
    };
    UsersService.prototype.update = function (userId, userDelta) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.update(userId, userDelta).then(function (response) { return response.user; })];
            });
        });
    };
    UsersService.prototype.get = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.get(userId).then(function (user) { return user; })];
            });
        });
    };
    UsersService.prototype.loadAll = function (request, commonOptions) {
        return __awaiter(this, void 0, void 0, function () {
            var limit, page_action, cursor;
            return __generator(this, function (_a) {
                limit = request.limit, page_action = request.page_action, cursor = request.cursor;
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.GET_ALL)
                        .withQueryString({ pgver: types_1.KEYSET_PAGINATION_VER, limit: limit, page_action: page_action, cursor: cursor })
                        .withExtractor(function (response) { return ({
                        next_page_cursor: response.next_page_cursor,
                        previous_page_cursor: response.previous_page_cursor,
                        users: response.users
                    }); })
                        .setException('Could not get users')
                        .withCommonOptions(commonOptions)
                        .invoke()];
            });
        });
    };
    UsersService.prototype.loadMany = function (query, commonOptions) {
        if (query === void 0) { query = {}; }
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.GET_ALL)
                        .withQueryString(query)
                        .withExtractor(function (response) { return response.users; })
                        .setException('Could not get users by ids')
                        .withCommonOptions(commonOptions)
                        .invoke()];
            });
        });
    };
    UsersService.prototype.loadAllByTeams = function (teamId, commonOptions) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.GET_DRIVERS_BY_TEAM)
                        .withRouteParams({ teamId: teamId })
                        .setException("failed to get teams drivers for team ".concat(teamId))
                        .withCommonOptions(commonOptions)
                        .invoke()];
            });
        });
    };
    /**
     * Generic method for keyset pagination with optional scoping
     */
    UsersService.prototype.getAllUsersWithKeysetPagination = function (request, scopes, exceptionMessage) {
        if (scopes === void 0) { scopes = []; }
        if (exceptionMessage === void 0) { exceptionMessage = 'Could not get users'; }
        return __awaiter(this, void 0, void 0, function () {
            var limit, page_action, cursor, options, queryParams;
            return __generator(this, function (_a) {
                limit = request.limit, page_action = request.page_action, cursor = request.cursor, options = request.options;
                // Add driver-specific scopes if options are provided
                if (options) {
                    if (options.onlyCustomers) {
                        scopes.push(User_consts_1.UsersScopes.CUSTOMERS);
                    }
                    else if (!scopes.includes(User_consts_1.UsersScopes.ADMINS) && !scopes.includes(User_consts_1.UsersScopes.DISPATCHERS)) {
                        // Only add DRIVERS scope if we're not already dealing with admins/dispatchers
                        scopes.push(User_consts_1.UsersScopes.DRIVERS);
                    }
                    if (options.onlyOnlineDriver) {
                        scopes.push(User_consts_1.UsersScopes.MARKED_AS_ONLINE);
                    }
                }
                queryParams = { pgver: '2', limit: limit, page_action: page_action, cursor: cursor };
                if (scopes.length > 0) {
                    queryParams.scopes = scopes;
                }
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.GET_ALL)
                        .withQueryString(queryParams)
                        .withExtractor(function (response) { return ({
                        next_page_cursor: response.next_page_cursor,
                        previous_page_cursor: response.previous_page_cursor,
                        users: response.users
                    }); })
                        .setException(exceptionMessage)
                        .invoke()];
            });
        });
    };
    UsersService.prototype.getAllDrivers = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.getAllUsersWithKeysetPagination(request, [], 'Could not get all drivers')];
            });
        });
    };
    UsersService.prototype.getAllAdminsAndDispatchers = function (request) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.getAllUsersWithKeysetPagination(request, [User_consts_1.UsersScopes.DISPATCHERS, User_consts_1.UsersScopes.ADMINS], 'Could not get all admins and dispatchers')];
            });
        });
    };
    UsersService.prototype.unlock = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .post(User_consts_1.ROUTES.UNLOCK)
                        .withRouteParams({ userId: userId })
                        .withExtractor(User_consts_1.successExtractor)
                        .setException("Could not unlock user with id: ".concat(userId))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.validatePhone = function (phone) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.VALIDATE_PHONE)
                        .withQueryString({ phone: phone })
                        .withExtractor(function (response) { return response.phone_valid; })
                        .setException("Phone is not valid: ".concat(phone))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.messageDriver = function (userId, message) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .put(User_consts_1.ROUTES.MESSAGE_DRIVER)
                        .withRouteParams({ userId: userId })
                        .withPayload({ user_id: userId, message: message })
                        .withExtractor(function (response) { return response.announcement_id; })
                        .setException("Could not message to user ".concat(userId))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.getDriverCost = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.DRIVER_COST)
                        .withRouteParams({ userId: userId })
                        .withExtractor(function (response) { return response; })
                        .setException("Could not get driver cost for user ".concat(userId))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.byUserType = function (userTypeId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .get(User_consts_1.ROUTES.GET_USERS_WITH_USER_TYPE)
                        .withRouteParams({ userTypeId: userTypeId })
                        .withExtractor(function (response) { return response.users; })
                        .setException("Could not get users with user type ".concat(userTypeId))
                        .invoke()];
            });
        });
    };
    UsersService.prototype.invite = function (userId) {
        return __awaiter(this, void 0, void 0, function () {
            return __generator(this, function (_a) {
                return [2 /*return*/, this.service.routeGenerator
                        .post(User_consts_1.ROUTES.INVITE)
                        .withRouteParams({ userId: userId })
                        .withExtractor(function (response) { return response.user; })
                        .setException("Could not invite user with id: ".concat(userId))
                        .invoke()];
            });
        });
    };
    return UsersService;
}());
exports.default = UsersService;
//# sourceMappingURL=users-service.js.map