"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.remove = exports.update = exports.logoutUser = exports.show = exports.store = exports.all = exports.index = void 0;
const socket_1 = require("../libs/socket");
const AppError_1 = __importDefault(require("../errors/AppError"));
const CreateUserService_1 = __importDefault(require("../services/UserServices/CreateUserService"));
const ListUsersService_1 = __importDefault(require("../services/UserServices/ListUsersService"));
const UpdateUserService_1 = __importDefault(require("../services/UserServices/UpdateUserService"));
const ShowUserService_1 = __importDefault(require("../services/UserServices/ShowUserService"));
const DeleteUserService_1 = __importDefault(require("../services/UserServices/DeleteUserService"));
const ListUserParamiterService_1 = __importDefault(require("../services/UserServices/ListUserParamiterService"));
const RedisClient_1 = require("../helpers/RedisClient");
const WhoIsOnlineMonitor_1 = require("../helpers/WhoIsOnlineMonitor");
const date_fns_1 = require("date-fns");
const locale_1 = require("date-fns/locale");
const CountTicketsByUserQueue_1 = __importDefault(require("../services/UserServices/CountTicketsByUserQueue"));
const SplitDateTime_1 = require("../helpers/SplitDateTime");
const ListUserByWhatsappQueuesService_1 = __importDefault(require("../services/UserServices/ListUserByWhatsappQueuesService"));
const WhaticketSettings_1 = require("../helpers/WhaticketSettings");
const SetBotInfo_1 = require("../helpers/SetBotInfo");
const index = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { searchParam, pageNumber, profile } = req.query;
    const { users, count, hasMore } = yield ListUsersService_1.default({
        searchParam,
        pageNumber,
        profile
    });
    if (req.user.profile !== "master") {
        let auxUsers = [];
        // for (var user of users) {
        //   if (user.profile !== 'master') {
        //     auxUsers.push(user)
        //   }
        // }
        for (var user of users) {
            if (user.profile !== "master") {
                if (req.user.profile == "supervisor" && user.profile == "admin")
                    continue;
                auxUsers.push(user);
            }
        }
        return res.json({ users: auxUsers, count, hasMore });
    }
    return res.json({ users, count, hasMore });
    //   const { users, count, hasMore } = await ListUsersService({
    //     searchParam,
    //     pageNumber
    //   });
    //   if(req.user.profile!=='master'){
    //     let auxUsers: Array<object>  = [];
    //     for (var user of users) {
    //       if(user.profile!=='master'){
    //         auxUsers.push(user)
    //       }
    //     }
    //     return res.json({ users: auxUsers, count, hasMore });
    //  }
    //   return res.json({ users, count, hasMore });
});
exports.index = index;
// export const usersByWhatsappQueue = async (req: Request, res: Response): Promise<Response> => {
//   const { profile } = req.query as IndexQuery;
//   const users = await ListUser({
//     profile
//   });
//   return res.json({ users });
// };
const all = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _a, _b;
    let { userId, profile, transferToOtherQueues } = req.query;
    console.log("userId: ", userId, " | profile: ", profile, ' | getSettingValue("queueTransferByWhatsappScope")?.value: ', (_a = WhaticketSettings_1.getSettingValue("queueTransferByWhatsappScope")) === null || _a === void 0 ? void 0 : _a.value);
    if (((_b = WhaticketSettings_1.getSettingValue("queueTransferByWhatsappScope")) === null || _b === void 0 ? void 0 : _b.value) == "enabled" && !transferToOtherQueues) {
        if (!userId)
            return res.json({ users: [], queues: [] });
        const obj = yield ListUserByWhatsappQueuesService_1.default(userId, '"admin", "user", "supervisor"');
        const usersByWhatsqueue = obj.users;
        const queues = obj.queues;
        let userIds = usersByWhatsqueue.map((w) => w.userId);
        const users = yield ListUserParamiterService_1.default({
            userIds
        });
        return res.json({ users, queues });
    }
    else {
        const users = yield ListUserParamiterService_1.default({
            profile
        });
        return res.json({ users });
    }
});
exports.all = all;
const store = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    var _c, _d;
    const { email, password, name, profile, positionId, queueIds, transferToOtherQueues } = req.body;
    console.log("===========> req.url: ", req.url);
    if (req.url === "/user" &&
        ((_c = WhaticketSettings_1.getSettingValue("userCreation")) === null || _c === void 0 ? void 0 : _c.value) == "disabled" &&
        req.user.profile == "admin") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    else if (req.url === "/signup" &&
        ((_d = WhaticketSettings_1.getSettingValue("userCreation")) === null || _d === void 0 ? void 0 : _d.value) == "disabled") {
        throw new AppError_1.default("ERR_USER_CREATION_DISABLED", 403);
    }
    else if (req.user.profile !== "master") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const user = yield CreateUserService_1.default({
        email,
        password,
        name,
        positionId,
        profile,
        queueIds,
        transferToOtherQueues
    });
    if (user) {
        const { id, name } = user;
        yield RedisClient_1.set(`user:${id}`, { id, name });
    }
    const io = socket_1.getIO();
    io.emit("user", {
        action: "create",
        user
    });
    // await stopWhoIsOnlineMonitor()
    yield WhoIsOnlineMonitor_1.startWhoIsOnlineMonitor();
    return res.status(200).json(user);
});
exports.store = store;
const show = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { userId } = req.params;
    const user = yield ShowUserService_1.default(userId);
    return res.status(200).json(user);
});
exports.show = show;
const logoutUser = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { userId } = req.params;
    yield WhoIsOnlineMonitor_1.stopWhoIsOnlineMonitor();
    let onlineTime = {
        userId: userId,
        status: "logout..."
    };
    const io = socket_1.getIO();
    io.emit("onlineStatus", {
        action: "logout",
        userOnlineTime: onlineTime
    });
    yield WhoIsOnlineMonitor_1.startWhoIsOnlineMonitor();
    //
    return res.status(200).json({});
});
exports.logoutUser = logoutUser;
const update = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    if (req.user.profile !== "admin" &&
        req.user.profile !== "master" &&
        req.user.profile !== "supervisor") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    const { userId } = req.params;
    const userData = req.body;
    const dateToday = SplitDateTime_1.splitDateTime(new Date(date_fns_1.format(new Date(), "yyyy-MM-dd HH:mm:ss", { locale: locale_1.ptBR })));
    const currentDate = new Date();
    const tenMonthsAgo = date_fns_1.subMonths(currentDate, 10);
    const formattedDate = date_fns_1.format(tenMonthsAgo, "yyyy-MM-dd");
    console.log("dateToday.fullDate: ", dateToday.fullDate);
    console.log("formattedDate 10 months ago: ", formattedDate);
    const openByUserOnQueue = yield CountTicketsByUserQueue_1.default({
        startDate: formattedDate,
        endDate: dateToday.fullDate,
        status: "open",
        clientChatStart: true,
        userId: userId
    });
    // console.log('------> openByUserOnQueue: ', openByUserOnQueue)
    // console.log()
    // console.log('------> 1 userData.queueIds: ', userData.queueIds)
    let userQueuesAttendance = [];
    if ((openByUserOnQueue && openByUserOnQueue.length) > 0) {
        userQueuesAttendance = openByUserOnQueue.filter((e) => !userData.queueIds.includes(e.queueId));
        if (userQueuesAttendance && userQueuesAttendance.length > 0) {
            const queueInAttendance = userQueuesAttendance.map(e => e.queueId);
            const mergedSet = new Set([...userData.queueIds, ...queueInAttendance]);
            // Convert the Set back to an array
            userData.queueIds = Array.from(mergedSet);
            // console.log('------> 2 userData.queueIds: ', userData.queueIds)
        }
    }
    let user = yield UpdateUserService_1.default({ userData, userId });
    yield SetBotInfo_1.setBotInfo(user);
    if (user) {
        const { id, name } = user;
        yield RedisClient_1.set(`user:${id}`, { id, name });
    }
    const io = socket_1.getIO();
    io.emit("user", {
        action: "update",
        user
    });
    user.userQueuesAttendance = userQueuesAttendance;
    return res.status(200).json(user);
});
exports.update = update;
const remove = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    const { userId } = req.params;
    if (req.user.profile !== "master") {
        throw new AppError_1.default("ERR_NO_PERMISSION", 403);
    }
    yield DeleteUserService_1.default(userId);
    RedisClient_1.del(`user:${userId}`);
    const io = socket_1.getIO();
    io.emit("user", {
        action: "delete",
        userId
    });
    //test del
    yield WhoIsOnlineMonitor_1.stopWhoIsOnlineMonitor();
    io.emit("onlineStatus", {
        action: "delete",
        userOnlineTime: userId
    });
    yield WhoIsOnlineMonitor_1.startWhoIsOnlineMonitor();
    //
    return res.status(200).json({ message: "User deleted" });
});
exports.remove = remove;
