"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || (function () {
    var ownKeys = function(o) {
        ownKeys = Object.getOwnPropertyNames || function (o) {
            var ar = [];
            for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
            return ar;
        };
        return ownKeys(o);
    };
    return function (mod) {
        if (mod && mod.__esModule) return mod;
        var result = {};
        if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
        __setModuleDefault(result, mod);
        return result;
    };
})();
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 __rest = (this && this.__rest) || function (s, e) {
    var t = {};
    for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
        t[p] = s[p];
    if (s != null && typeof Object.getOwnPropertySymbols === "function")
        for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
            if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
                t[p[i]] = s[p[i]];
        }
    return t;
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.currentUser = currentUser;
exports.getNotifications = getNotifications;
exports.readNotification = readNotification;
exports.editPersonalInformation = editPersonalInformation;
exports.editOtherInformation = editOtherInformation;
exports.editPassword = editPassword;
const bcrypt = __importStar(require("bcrypt"));
const consts_1 = require("../../utils/consts");
const prisma_1 = __importDefault(require("../../utils/prisma"));
const string_1 = require("../../utils/string");
// ------------------------------------------------------------------------------------
function currentUser(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const fullUser = yield prisma_1.default.user.findUnique({
            where: { id: userId, active: true },
            include: {
                company: {
                    include: {
                        city: true,
                        contactPosition: true,
                        nEmployees: true,
                        turnover: true,
                    },
                },
                position: true,
                city: true,
            },
        });
        if (!fullUser) {
            return reply.code(401).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        if (fullUser.company && !fullUser.company.active) {
            return reply.code(401).send({
                message: "Votre entreprise a été desactivé par la CCIS",
            });
        }
        yield prisma_1.default.user.update({
            where: { id: userId },
            data: { loggedInAt: new Date() },
        });
        const nNotifications = yield prisma_1.default.notification.count({
            where: { isRead: false, userId },
        });
        const _a = Object.assign(Object.assign({}, fullUser), { nNotifications }), { password } = _a, user = __rest(_a, ["password"]);
        return reply.code(200).send(user);
    });
}
// ------------------------------------------------------------------------------------
function getNotifications(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        var _a;
        const userId = req.user.id;
        const page = (_a = (0, string_1.stringToInt)(req.query.page)) !== null && _a !== void 0 ? _a : 0;
        const skipedRows = consts_1.N_ITEMS_PER_PAGE * page;
        const nNotifications = yield prisma_1.default.notification.count({
            where: { userId },
        });
        const nPages = Math.ceil(nNotifications / consts_1.N_ITEMS_PER_PAGE);
        const notifications = yield prisma_1.default.notification.findMany({
            where: { userId },
            take: consts_1.N_ITEMS_PER_PAGE,
            skip: skipedRows,
            orderBy: {
                createdAt: "desc",
            },
        });
        return reply.code(200).send({ page, nPages, notifications });
    });
}
// ------------------------------------------------------------------------------------
function readNotification(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const id = req.params.id;
        try {
            yield prisma_1.default.notification.update({
                where: {
                    userId: userId,
                    id: id,
                },
                data: {
                    isRead: true,
                },
            });
        }
        catch (_a) {
            return reply.code(404).send({
                message: "La notification n'existe pas",
            });
        }
        return reply.code(200).send({});
    });
}
// ------------------------------------------------------------------------------------
function editPersonalInformation(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const user = yield prisma_1.default.user.findUnique({
            where: { id: userId, active: true },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const data = req.body;
        const city = yield prisma_1.default.city.findUnique({
            where: {
                id: data.cityId,
            },
        });
        if (!city) {
            return reply.code(400).send({
                message: "La ville n'existe pas",
            });
        }
        const position = yield prisma_1.default.position.findUnique({
            where: {
                id: data.positionId,
            },
        });
        if (!position) {
            return reply.code(400).send({
                message: "La fonction n'existe pas",
            });
        }
        const newUserFull = yield prisma_1.default.user.update({
            where: { id: userId },
            data: {
                civility: data.civility,
                firstName: data.firstName,
                lastName: data.lastName,
                cityId: data.cityId,
                positionId: data.positionId,
                phoneNumber: data.phoneNumber,
            },
        });
        const { password } = newUserFull, newUser = __rest(newUserFull, ["password"]);
        return reply.code(200).send(newUser);
    });
}
// ------------------------------------------------------------------------------------
function editOtherInformation(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const user = yield prisma_1.default.user.findUnique({
            where: { id: userId, active: true },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const data = req.body;
        const newUserFull = yield prisma_1.default.user.update({
            where: { id: userId },
            data: {
                bio: data.bio,
                expertiseAreas: data.expertiseAreas,
                interestAreas: data.interestAreas,
            },
        });
        const { password } = newUserFull, newUser = __rest(newUserFull, ["password"]);
        return reply.code(200).send(newUser);
    });
}
// ------------------------------------------------------------------------------------
function editPassword(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const user = yield prisma_1.default.user.findUnique({
            where: { id: userId, active: true },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const data = req.body;
        const isMatch = yield bcrypt.compare(data.old_password, user.password);
        if (!isMatch) {
            return reply.code(400).send({
                message: "L'ancien mot de passe est incorrect",
            });
        }
        const hash = yield bcrypt.hash(data.new_password, consts_1.SALT_ROUNDS);
        yield prisma_1.default.user.update({
            where: { id: userId },
            data: {
                password: hash,
            },
        });
        return reply.code(200).send({});
    });
}
