"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 __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getElectedMembers = getElectedMembers;
exports.getElectedMember = getElectedMember;
exports.createElectedMember = createElectedMember;
exports.editElectedMember = editElectedMember;
exports.editElectedMemebrActive = editElectedMemebrActive;
exports.editElectedMemberPassword = editElectedMemberPassword;
exports.sendNotification = sendNotification;
exports.sendEmail = sendEmail;
exports.sendSms = sendSms;
exports.deleteElectedMember = deleteElectedMember;
const prisma_1 = __importDefault(require("../../utils/prisma"));
const consts_1 = require("../../utils/consts");
const mail_1 = require("../../utils/mail");
const client_1 = require("@prisma/client");
const bcrypt = __importStar(require("bcrypt"));
const axios_1 = __importDefault(require("axios"));
const env_1 = require("../../utils/env");
// ------------------------------------------------------------------------------------
function getElectedMembers(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const electedMembers = yield prisma_1.default.user.findMany({
            where: {
                role: client_1.$Enums.Role.ElectedMember,
            },
            orderBy: {
                lastName: "asc",
            },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                active: true,
                phoneNumber: true,
                position: true,
                createdAt: true,
            },
        });
        return reply.code(200).send(electedMembers);
    });
}
// ------------------------------------------------------------------------------------
function getElectedMember(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const electedMember = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.ElectedMember,
            },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                phoneNumber: true,
                positionId: true,
                position: true,
                active: true,
                createdAt: true,
                adresse: true,
                college: true,
                collegeId: true,
                province: true,
                provinceId: true,
                mandate: true,
                mandateId: true,
                commissions: true,
                details: true,
            },
        });
        if (!electedMember) {
            return reply.code(404).send({
                message: "Ce membre élu n'existe pas",
            });
        }
        return reply.code(200).send(electedMember);
    });
}
// ------------------------------------------------------------------------------------
// export async function uploadElectedMemberImage(
//   req: FastifyRequest<{ Body: MinioImageSchema }>,
//   reply: FastifyReply
// ) {
//   const data = req.body;
//   const buffer = await data.image.toBuffer();
//   const ext = data.image.filename.split(".").pop();
//   const mimetype = data.image.mimetype;
//   const fileName = "elected-members/" + uuid() + "." + ext;
//   await minioClient.putObject(bucketName, fileName, buffer, undefined, {
//     "Content-Type": mimetype,
//   });
//   const presignedUrl = await getPresignedUrl(fileName);
//   return reply
//     .code(200)
//     .send({ image: fileName, presignedImage: presignedUrl });
// }
// ------------------------------------------------------------------------------------
function createElectedMember(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        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 college = yield prisma_1.default.college.findUnique({
            where: {
                id: data.collegeId,
            },
        });
        if (!college) {
            return reply.code(404).send({
                message: "Le collège n'existe pas",
            });
        }
        const province = yield prisma_1.default.province.findUnique({
            where: {
                id: data.provinceId,
            },
        });
        if (!province) {
            return reply.code(404).send({
                message: "La province n'existe pas",
            });
        }
        const mandate = yield prisma_1.default.mandate.findUnique({
            where: {
                id: data.mandateId,
            },
        });
        if (!mandate) {
            return reply.code(404).send({
                message: "Le mandat n'existe pas",
            });
        }
        const user = yield prisma_1.default.user.findUnique({
            where: {
                email: data.email.toLowerCase(),
            },
        });
        if (user) {
            return reply.code(400).send({
                message: "Un autre utilisateur/membre élu/fontionnaire avec cette adresse mail existe déjà",
            });
        }
        const hash = yield bcrypt.hash(data.password, consts_1.SALT_ROUNDS);
        const electedMember = yield prisma_1.default.user.create({
            data: {
                civility: data.civility,
                firstName: data.firstName,
                lastName: data.lastName,
                positionId: data.positionId,
                phoneNumber: data.phoneNumber,
                adresse: data.adresse,
                email: data.email.toLowerCase(),
                password: hash,
                collegeId: data.collegeId,
                provinceId: data.provinceId,
                mandateId: data.mandateId,
                commissions: data.commissions,
                details: data.details,
                role: client_1.$Enums.Role.ElectedMember,
                bio: "",
            },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                active: true,
                phoneNumber: true,
                position: true,
                createdAt: true,
            },
        });
        return reply.code(200).send(electedMember);
    });
}
// ------------------------------------------------------------------------------------
function editElectedMember(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        const id = req.params.id;
        const electedMember = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.ElectedMember,
            },
        });
        if (!electedMember) {
            return reply.code(404).send({
                message: "Ce membre élu 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 college = yield prisma_1.default.college.findUnique({
            where: {
                id: data.collegeId,
            },
        });
        if (!college) {
            return reply.code(404).send({
                message: "Le collège n'existe pas",
            });
        }
        const province = yield prisma_1.default.province.findUnique({
            where: {
                id: data.provinceId,
            },
        });
        if (!province) {
            return reply.code(404).send({
                message: "La province n'existe pas",
            });
        }
        const mandate = yield prisma_1.default.mandate.findUnique({
            where: {
                id: data.mandateId,
            },
        });
        if (!mandate) {
            return reply.code(404).send({
                message: "Le mandat n'existe pas",
            });
        }
        const nUsers = yield prisma_1.default.user.count({
            where: {
                id: { not: electedMember.id },
                email: data.email.toLowerCase(),
            },
        });
        if (nUsers > 0) {
            return reply.code(400).send({
                message: "Un autre utilisateur/membre élu/fontionnaire avec cette adresse mail existe déjà",
            });
        }
        const newElectedMember = yield prisma_1.default.user.update({
            where: {
                id: electedMember.id,
                role: client_1.$Enums.Role.ElectedMember,
            },
            data: {
                civility: data.civility,
                firstName: data.firstName,
                lastName: data.lastName,
                positionId: data.positionId,
                phoneNumber: data.phoneNumber,
                adresse: data.adresse,
                email: data.email.toLowerCase(),
                collegeId: data.collegeId,
                provinceId: data.provinceId,
                mandateId: data.mandateId,
                commissions: data.commissions,
                details: data.details,
            },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                active: true,
                phoneNumber: true,
                position: true,
                createdAt: true,
            },
        });
        return reply.code(200).send(newElectedMember);
    });
}
// ------------------------------------------------------------------------------------
function editElectedMemebrActive(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const data = req.body;
        const electedMember = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.ElectedMember,
            },
        });
        if (!electedMember) {
            return reply.code(404).send({
                message: "Ce membre élu n'existe pas",
            });
        }
        const newElectedMember = yield prisma_1.default.user.update({
            where: { id: id, role: client_1.$Enums.Role.ElectedMember },
            data: {
                active: data.active,
            },
        });
        return reply.code(200).send({ active: newElectedMember.active });
    });
}
// ------------------------------------------------------------------------------------
function editElectedMemberPassword(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const data = req.body;
        const electedMember = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.ElectedMember,
            },
        });
        if (!electedMember) {
            return reply.code(404).send({
                message: "Ce memebre élu n'existe pas",
            });
        }
        const hash = yield bcrypt.hash(data.password, consts_1.SALT_ROUNDS);
        yield prisma_1.default.user.update({
            where: { id: id },
            data: {
                password: hash,
            },
        });
        return reply.code(200).send({});
    });
}
// -------------------------------------------------------------------------
function sendNotification(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        const electedMembers = yield prisma_1.default.user.findMany({
            where: {
                id: { in: data.electedMembers },
                role: client_1.$Enums.Role.ElectedMember,
            },
            select: { id: true },
        });
        yield Promise.all(electedMembers.map((electedMember) => __awaiter(this, void 0, void 0, function* () {
            yield prisma_1.default.notification.create({
                data: {
                    title: "Message de l'administration",
                    content: data.content,
                    userId: electedMember.id,
                    source: client_1.$Enums.Source.Administration,
                },
            });
        })));
        return reply.code(200).send({});
    });
}
// ------------------------------------------------------------------------------------
function sendEmail(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        const electedMembers = yield prisma_1.default.user.findMany({
            where: {
                id: { in: data.electedMembers },
                role: client_1.$Enums.Role.ElectedMember,
            },
            select: { email: true },
        });
        electedMembers.map((electedMember) => {
            const mailOptions = {
                from: process.env.EMAIL_HOST_USER,
                to: electedMember.email,
                subject: data.subject,
                html: data.body,
            };
            try {
                mail_1.mail.sendMail(mailOptions);
            }
            catch (_a) { }
        });
        return reply.code(200).send({});
    });
}
// -------------------------------------------------------------------------
function sendSms(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        const electedMembers = yield prisma_1.default.user.findMany({
            where: {
                id: { in: data.electedMembers },
                role: client_1.$Enums.Role.ElectedMember,
            },
            select: { phoneNumber: true },
        });
        try {
            yield Promise.all(electedMembers.map((electedMember) => __awaiter(this, void 0, void 0, function* () {
                const phoneNumber = `+212${electedMember.phoneNumber.slice(1)}`;
                yield axios_1.default.post("https://api.releans.com/v2/message", {
                    sender: "CCIS",
                    mobile: phoneNumber,
                    content: data.content,
                }, {
                    headers: {
                        Authorization: `Bearer ${env_1.releansApiKey}`,
                    },
                });
            })));
        }
        catch (_a) {
            return reply.code(400).send({ message: "Erreur lors de l'envoie du SMS" });
        }
        return reply.code(200).send({});
    });
}
// ------------------------------------------------------------------------------------
function deleteElectedMember(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const electedMember = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.ElectedMember,
            },
        });
        if (!electedMember) {
            return reply.code(404).send({
                message: "Ce membre élu n'existe pas",
            });
        }
        try {
            yield prisma_1.default.user.delete({
                where: { id: id },
            });
        }
        catch (_a) {
            return reply.code(400).send({
                message: "Vouis pouvez pas supprimer un membre élu",
            });
        }
        return reply.code(200).send({});
    });
}
// ------------------------------------------------------------------------------------
