"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.getCompanies = getCompanies;
exports.getCompany = getCompany;
exports.getUsers = getUsers;
exports.getMyNetwork = getMyNetwork;
exports.getUser = getUser;
exports.sendConnection = sendConnection;
exports.acceptDeclineConnection = acceptDeclineConnection;
exports.deleteConnection = deleteConnection;
const prisma_1 = __importDefault(require("../../utils/prisma"));
const client_1 = require("@prisma/client");
// ------------------------------------------------------------------------------------
function getCompanies(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const companies = yield prisma_1.default.company.findMany({
            where: { active: true, verified: true },
            select: {
                id: true,
                name: true,
                legalForm: true,
                city: true,
                turnover: true,
                nEmployees: true,
                activities: true,
                activitiesFamilies: true,
            },
            orderBy: {
                name: "asc",
            },
        });
        return reply.code(200).send(companies);
    });
}
// ------------------------------------------------------------------------------------
function getCompany(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const company = yield prisma_1.default.company.findUnique({
            where: { id: id, active: true },
            include: {
                users: {
                    select: {
                        id: true,
                        firstName: true,
                        lastName: true,
                        position: true,
                    },
                },
                city: true,
                contactPosition: true,
                nEmployees: true,
                turnover: true,
            },
        });
        if (!company) {
            return reply.code(404).send({
                message: "Cette entreprise n'existe pas",
            });
        }
        return reply.code(200).send(company);
    });
}
// ------------------------------------------------------------------------------------
function getUsers(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const users = yield prisma_1.default.user.findMany({
            where: { active: true, role: client_1.$Enums.Role.User },
            select: {
                id: true,
                firstName: true,
                lastName: true,
                position: true,
                expertiseAreas: true,
                interestAreas: true,
                member: true,
            },
            orderBy: {
                firstName: "asc",
            },
        });
        return reply.code(200).send(users);
    });
}
// ------------------------------------------------------------------------------------
function getMyNetwork(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const users = yield prisma_1.default.user.findMany({
            where: {
                active: true,
                role: client_1.$Enums.Role.User,
                id: { not: userId },
                OR: [
                    {
                        connectionsReceived: {
                            some: {
                                OR: [{ senderId: userId }, { receiverId: userId }],
                                accepted: true,
                            },
                        },
                    },
                    {
                        connectionsSent: {
                            some: {
                                OR: [{ senderId: userId }, { receiverId: userId }],
                                accepted: true,
                            },
                        },
                    },
                ],
            },
            select: {
                id: true,
                firstName: true,
                lastName: true,
                position: true,
                expertiseAreas: true,
                interestAreas: true,
            },
            orderBy: {
                firstName: "asc",
            },
        });
        return reply.code(200).send(users);
    });
}
// ------------------------------------------------------------------------------------
function getUser(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const userId = req.user.id;
        const user = yield prisma_1.default.user.findUnique({
            where: { id, role: client_1.$Enums.Role.User },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                company: true,
                position: true,
                expertiseAreas: true,
                interestAreas: true,
                member: true,
                loggedInAt: true,
            },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const connection = yield prisma_1.default.connection.findFirst({
            where: {
                OR: [
                    { senderId: userId, receiverId: user.id },
                    { senderId: user.id, receiverId: userId },
                ],
            },
        });
        return reply.code(200).send(Object.assign(Object.assign({}, user), { connection, isOnline: user.loggedInAt &&
                new Date().getTime() - user.loggedInAt.getTime() <= 20 * 60 * 1000 }));
    });
}
// ------------------------------------------------------------------------------------
function sendConnection(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const userId = req.user.id;
        if (id === userId) {
            return reply.code(404).send({
                message: "Tu ne peux pas te connecter avec toi-même",
            });
        }
        const user = yield prisma_1.default.user.findUnique({
            where: { id: id, active: true, role: client_1.$Enums.Role.User },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const nConnections = yield prisma_1.default.connection.count({
            where: {
                OR: [
                    { senderId: userId, receiverId: id },
                    { senderId: id, receiverId: userId },
                ],
            },
        });
        if (nConnections > 0) {
            return reply.code(400).send({
                message: "La demande de connexion existe déjà",
            });
        }
        const connection = yield prisma_1.default.connection.create({
            data: {
                senderId: userId,
                receiverId: id,
            },
        });
        return reply.code(200).send(connection);
    });
}
// ------------------------------------------------------------------------------------
function acceptDeclineConnection(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const id = req.params.id;
        const data = req.body;
        const user = yield prisma_1.default.user.findUnique({
            where: { id: id, active: true, role: client_1.$Enums.Role.User },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const connection = yield prisma_1.default.connection.findFirst({
            where: {
                senderId: id,
                receiverId: userId,
            },
        });
        if (!connection) {
            return reply.code(404).send({
                message: "Cette connection n'existe pas",
            });
        }
        if (data.accepted) {
            const newConnection = yield prisma_1.default.connection.update({
                where: {
                    id: connection.id,
                },
                data: {
                    accepted: true,
                },
            });
            return reply.code(200).send(newConnection);
        }
        else {
            yield prisma_1.default.connection.delete({
                where: {
                    id: connection.id,
                },
            });
            return reply.code(200).send(null);
        }
    });
}
// ------------------------------------------------------------------------------------
function deleteConnection(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const id = req.params.id;
        const user = yield prisma_1.default.user.findUnique({
            where: { id: id, active: true, role: client_1.$Enums.Role.User },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const connection = yield prisma_1.default.connection.findFirst({
            where: {
                OR: [
                    { senderId: userId, receiverId: id },
                    { senderId: id, receiverId: userId },
                ],
            },
        });
        if (!connection) {
            return reply.code(404).send({
                message: "Cette connection n'existe pas",
            });
        }
        yield prisma_1.default.connection.delete({ where: { id: connection.id } });
        return reply.code(200).send({});
    });
}
