"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.destroy = exports.update = exports.read = exports.create = exports.search = void 0;
const workerRequests_1 = require("../../../utilities/workerRequests");
const users_1 = require("../../../utilities/users");
const utils_1 = require("./utils");
function getUser(ctx, userId) {
    var _a;
    if (userId) {
        ctx.params = { userId };
    }
    else if (!((_a = ctx.params) === null || _a === void 0 ? void 0 : _a.userId)) {
        throw "No user ID provided for getting";
    }
    return (0, workerRequests_1.readGlobalUser)(ctx);
}
function search(ctx, next) {
    return __awaiter(this, void 0, void 0, function* () {
        const { name } = ctx.request.body;
        const users = yield (0, workerRequests_1.allGlobalUsers)(ctx);
        ctx.body = (0, utils_1.search)(users, name, "email");
        yield next();
    });
}
exports.search = search;
function create(ctx, next) {
    return __awaiter(this, void 0, void 0, function* () {
        const response = yield (0, workerRequests_1.saveGlobalUser)((0, users_1.publicApiUserFix)(ctx));
        ctx.body = yield getUser(ctx, response._id);
        yield next();
    });
}
exports.create = create;
function read(ctx, next) {
    return __awaiter(this, void 0, void 0, function* () {
        ctx.body = yield (0, workerRequests_1.readGlobalUser)(ctx);
        yield next();
    });
}
exports.read = read;
function update(ctx, next) {
    return __awaiter(this, void 0, void 0, function* () {
        const user = yield (0, workerRequests_1.readGlobalUser)(ctx);
        ctx.request.body = Object.assign(Object.assign({}, ctx.request.body), { _rev: user._rev });
        const response = yield (0, workerRequests_1.saveGlobalUser)((0, users_1.publicApiUserFix)(ctx));
        ctx.body = yield getUser(ctx, response._id);
        yield next();
    });
}
exports.update = update;
function destroy(ctx, next) {
    return __awaiter(this, void 0, void 0, function* () {
        const user = yield getUser(ctx);
        yield (0, workerRequests_1.deleteGlobalUser)(ctx);
        ctx.body = user;
        yield next();
    });
}
exports.destroy = destroy;
exports.default = {
    create,
    read,
    update,
    destroy,
    search,
};
