"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 __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.getOpportunities = getOpportunities;
exports.getMyOpportunities = getMyOpportunities;
exports.getOpportunity = getOpportunity;
exports.createOpportunity = createOpportunity;
exports.editOpportunity = editOpportunity;
exports.editOpportunityActive = editOpportunityActive;
exports.deleteOpportunity = deleteOpportunity;
exports.opportunityLike = opportunityLike;
exports.opportunityComment = opportunityComment;
const client_1 = require("@prisma/client");
const minio_1 = require("../../utils/minio");
const prisma_1 = __importDefault(require("../../utils/prisma"));
// ------------------------------------------------------------------------------------
function getOpportunities(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const opportunities = yield prisma_1.default.opportunity.findMany({
            where: {
                active: true,
                verified: true,
                OR: [
                    {
                        validityDate: null,
                    },
                    {
                        validityDate: {
                            gte: new Date(),
                        },
                    },
                ],
            },
            orderBy: {
                createdAt: "desc",
            },
            select: {
                id: true,
                title: true,
                companyName: true,
                createdAt: true,
                active: true,
                verified: true,
            },
        });
        return reply.code(200).send(opportunities);
    });
}
// ------------------------------------------------------------------------------------
function getMyOpportunities(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const opportunities = yield prisma_1.default.opportunity.findMany({
            where: { creatorId: userId },
            orderBy: {
                createdAt: "desc",
            },
            select: {
                id: true,
                title: true,
                companyName: true,
                createdAt: true,
                active: true,
                verified: true,
            },
        });
        return reply.code(200).send(opportunities);
    });
}
// ------------------------------------------------------------------------------------
function getOpportunity(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const id = req.params.id;
        const fullOpportunity = yield prisma_1.default.opportunity.findUnique({
            where: {
                id: id,
                AND: [
                    {
                        OR: [
                            { active: true },
                            {
                                creatorId: userId,
                            },
                        ],
                    },
                    {
                        OR: [
                            {
                                validityDate: null,
                            },
                            {
                                validityDate: {
                                    gte: new Date(),
                                },
                            },
                            {
                                creatorId: userId,
                            },
                        ],
                    },
                ],
            },
            include: {
                creator: {
                    select: {
                        id: true,
                        firstName: true,
                        lastName: true,
                        position: true,
                        role: true,
                    },
                },
                comments: {
                    orderBy: { createdAt: "asc" },
                    include: {
                        user: {
                            select: {
                                id: true,
                                firstName: true,
                                lastName: true,
                            },
                        },
                    },
                },
                likes: true,
            },
        });
        if (!fullOpportunity) {
            return reply.code(404).send({
                message: "Cette opportunité n'existe pas",
            });
        }
        const finalOpportunity = Object.assign(Object.assign({}, fullOpportunity), { presignedDocument: fullOpportunity.document
                ? yield (0, minio_1.getPresignedUrl)(fullOpportunity.document)
                : null });
        const { creator } = finalOpportunity, opportunity = __rest(finalOpportunity, ["creator"]);
        if (creator.role !== client_1.$Enums.Role.Admin) {
            return reply.code(200).send(finalOpportunity);
        }
        return reply.code(200).send(opportunity);
    });
}
// ------------------------------------------------------------------------------------
function createOpportunity(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const data = req.body;
        const opportunity = yield prisma_1.default.opportunity.create({
            data: {
                title: data.title,
                description: data.description,
                companyName: data.companyName,
                activitiesFamilies: data.activitiesFamilies,
                activities: data.activities,
                country: data.country,
                address: data.address,
                requirements: data.requirements,
                contactEmail: data.contactEmail,
                contactPhoneNumber: data.contactPhoneNumber,
                creatorId: userId,
                validityDate: data.validityDate,
            },
            select: {
                id: true,
                title: true,
                companyName: true,
                createdAt: true,
                active: true,
                verified: true,
            },
        });
        return reply.code(200).send(opportunity);
    });
}
// ------------------------------------------------------------------------------------
function editOpportunity(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 opportunity = yield prisma_1.default.opportunity.findUnique({
            where: {
                id: id,
                creatorId: userId,
            },
        });
        if (!opportunity) {
            return reply.code(404).send({
                message: "Cette opportunité n'existe pas",
            });
        }
        const newOpportunity = yield prisma_1.default.opportunity.update({
            where: { id: id },
            data: {
                title: data.title,
                description: data.description,
                companyName: data.companyName,
                activitiesFamilies: data.activitiesFamilies,
                activities: data.activities,
                country: data.country,
                address: data.address,
                requirements: data.requirements,
                contactEmail: data.contactEmail,
                contactPhoneNumber: data.contactPhoneNumber,
                creatorId: userId,
                validityDate: data.validityDate,
            },
            select: {
                id: true,
                title: true,
                companyName: true,
                createdAt: true,
                active: true,
                verified: true,
            },
        });
        return reply.code(200).send(newOpportunity);
    });
}
// ------------------------------------------------------------------------------------
function editOpportunityActive(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 opportunity = yield prisma_1.default.opportunity.findUnique({
            where: {
                id: id,
                creatorId: userId,
            },
        });
        if (!opportunity) {
            return reply.code(404).send({
                message: "Cette opportunité n'existe pas",
            });
        }
        yield prisma_1.default.opportunity.update({
            where: { id: id },
            data: {
                active: data.active,
            },
        });
        return reply.code(200).send({ active: data.active });
    });
}
// ------------------------------------------------------------------------------------
function deleteOpportunity(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const id = req.params.id;
        const opportunity = yield prisma_1.default.opportunity.findUnique({
            where: {
                id: id,
                creatorId: userId,
            },
        });
        if (!opportunity) {
            return reply.code(404).send({
                message: "Cette opportunité n'existe pas",
            });
        }
        yield prisma_1.default.opportunity.delete({
            where: { id: id },
        });
        return reply.code(200).send({});
    });
}
// ------------------------------------------------------------------------------------
function opportunityLike(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const userId = req.user.id;
        const id = req.params.id;
        const opportunity = yield prisma_1.default.opportunity.findUnique({
            where: {
                id: id,
            },
        });
        if (!opportunity) {
            return reply.code(404).send({
                message: "Cette opportunité n'existe pas",
            });
        }
        const oldOpportunityLike = yield prisma_1.default.opportunityLike.findFirst({
            where: {
                opportunityId: opportunity.id,
                userId: userId,
            },
        });
        if (oldOpportunityLike) {
            yield prisma_1.default.opportunityLike.delete({
                where: {
                    id: oldOpportunityLike.id,
                },
            });
            return reply.code(200).send(null);
        }
        const opportunityLike = yield prisma_1.default.opportunityLike.create({
            data: {
                opportunityId: opportunity.id,
                userId: userId,
            },
        });
        return reply.code(200).send(opportunityLike);
    });
}
// ------------------------------------------------------------------------------------
function opportunityComment(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 opportunity = yield prisma_1.default.opportunity.findUnique({
            where: {
                id: id,
            },
        });
        if (!opportunity) {
            return reply.code(404).send({
                message: "Cette opportunité n'existe pas",
            });
        }
        const opportunityComment = yield prisma_1.default.opportunityComment.create({
            data: {
                opportunityId: opportunity.id,
                userId: userId,
                content: data.content,
            },
            include: {
                user: {
                    select: {
                        id: true,
                        firstName: true,
                        lastName: true,
                    },
                },
            },
        });
        return reply.code(200).send(opportunityComment);
    });
}
// ------------------------------------------------------------------------------------
