"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.getAppointments = getAppointments;
exports.getAppointmentsHome = getAppointmentsHome;
exports.getEvents = getEvents;
exports.getEventsHome = getEventsHome;
exports.getFairs = getFairs;
exports.getSupportOffers = getSupportOffers;
exports.getCompaniesSync = getCompaniesSync;
exports.getUsersSync = getUsersSync;
exports.getOpportunitiesSync = getOpportunitiesSync;
exports.getAppointmentsSync = getAppointmentsSync;
exports.getEventsSync = getEventsSync;
exports.getAlbumsSync = getAlbumsSync;
exports.getVideosSync = getVideosSync;
exports.getEditionsSync = getEditionsSync;
exports.getTrainingsSync = getTrainingsSync;
exports.getFairsSync = getFairsSync;
const axios_1 = __importDefault(require("axios"));
const prisma_1 = __importDefault(require("../../utils/prisma"));
const client_1 = require("@prisma/client");
const minio_1 = require("../../utils/minio");
const env_1 = require("../../utils/env");
// ------------------------------------------------------------------------------------
function getAppointments(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const data = (yield axios_1.default.get("https://ccis-agadir.ma/wp-json/fat-event/v1/get_all_events_ccis")).data;
            const now = new Date();
            const appointments = data
                .filter((appointment) => {
                const endDate = new Date(parseInt(appointment.endDate) * 1000);
                return (endDate >= now && !appointment.categories.includes("Foire et salon"));
            })
                .map((appointment) => (Object.assign(Object.assign({}, appointment), { startDate: new Date(parseInt(appointment.startDate) * 1000), endDate: new Date(parseInt(appointment.endDate) * 1000), date: new Date(appointment.date * 1000) })));
            return reply.code(200).send(appointments);
        }
        catch (_a) {
            return reply.code(200).send([]);
        }
    });
}
// ------------------------------------------------------------------------------------
function getAppointmentsHome(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const data = (yield axios_1.default.get("https://ccis-agadir.ma/wp-json/fat-event/v1/get_all_events_ccis")).data;
            const now = new Date();
            const appointments = data
                .filter((appointment) => {
                const endDate = new Date(parseInt(appointment.endDate) * 1000);
                return (endDate >= now && !appointment.categories.includes("Foire et salon"));
            })
                .slice(0, 5)
                .map((appointment) => (Object.assign(Object.assign({}, appointment), { startDate: new Date(parseInt(appointment.startDate) * 1000), endDate: new Date(parseInt(appointment.endDate) * 1000), date: new Date(appointment.date * 1000) })));
            return reply.code(200).send(appointments);
        }
        catch (_a) {
            return reply.code(200).send([]);
        }
    });
}
// ------------------------------------------------------------------------------------
function getEvents(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const data = (yield axios_1.default.get("https://ccis-agadir.ma/wp-json/fat-event/v1/get_all_posts_ccis")).data;
            const events = data.map((event) => (Object.assign(Object.assign({}, event), { date: new Date(event.date * 1000) })));
            return reply.code(200).send(events);
        }
        catch (_a) {
            return reply.code(200).send([]);
        }
    });
}
// ------------------------------------------------------------------------------------
function getEventsHome(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const data = (yield axios_1.default.get("https://ccis-agadir.ma/wp-json/fat-event/v1/get_all_posts_ccis")).data;
            const events = data.slice(0, 5).map((event) => (Object.assign(Object.assign({}, event), { date: new Date(event.date * 1000) })));
            return reply.code(200).send(events);
        }
        catch (_a) {
            return reply.code(200).send([]);
        }
    });
}
// ------------------------------------------------------------------------------------
function getFairs(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            const data = (yield axios_1.default.get("https://ccis-agadir.ma/wp-json/fat-event/v1/get_all_events_ccis")).data;
            const fairs = data
                .filter((fair) => {
                return fair.categories.includes("Foire et salon");
            })
                .map((fair) => (Object.assign(Object.assign({}, fair), { startDate: new Date(parseInt(fair.startDate) * 1000), endDate: new Date(parseInt(fair.endDate) * 1000), date: new Date(fair.date * 1000) })));
            return reply.code(200).send(fairs);
        }
        catch (_a) {
            return reply.code(200).send([]);
        }
    });
}
// ------------------------------------------------------------------------------------
function getSupportOffers(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        try {
            console.time("part1");
            const data = (yield axios_1.default.get("https://ccis-agadir.ma/wp-json/gf/v2/forms/6/entries/", {
                auth: {
                    username: env_1.gfApiKey,
                    password: env_1.gfApiSecret,
                },
            })).data;
            console.timeEnd("part1");
            const supportOffers = data.entries.map((entry) => ({
                id: entry.id,
                serviceCode: entry[1],
                type: [
                    entry[26.1],
                    entry[26.2],
                    entry[26.3],
                    entry[26.4],
                    entry[26.5],
                    entry[26.6],
                    entry[26.7],
                    entry[26.8],
                    entry[26.9],
                    entry[26.11],
                ].filter((item) => item !== ""),
                serviceName: entry[4],
                organization: [
                    entry[28.1],
                    entry[28.2],
                    entry[28.3],
                    entry[28.4],
                    entry[28.5],
                    entry[28.6],
                    entry[28.7],
                    entry[28.8],
                    entry[28.9],
                    entry[28.11],
                    entry[28.12],
                    entry[28.13],
                    entry[28.14],
                    entry[28.15],
                    entry[28.16],
                    entry[28.17],
                ].filter((item) => item !== ""),
                organizationCategory: [entry[27.1], entry[27.2], entry[27.3]].filter((item) => item !== ""),
                concernedSector: [
                    entry[29.1],
                    entry[29.2],
                    entry[29.3],
                    entry[29.4],
                    entry[29.5],
                    entry[29.6],
                    entry[29.7],
                    entry[29.8],
                    entry[29.9],
                    entry[29.11],
                    entry[29.12],
                ].filter((item) => item !== ""),
                offerSubject: entry[8],
                eligibleOrganizations: [entry[30.1], entry[30.2], entry[30.3]].filter((item) => item !== ""),
                eligibleFunding: entry[10],
                project: entry[11],
                guaranteedCompetitions: entry[12],
                Conditions: entry[13],
                keyPrincipale: entry[14],
                processingTime: entry[15],
                ceiling: entry[16],
                financingQuota: entry[17],
                guaranteeDuration: entry[31],
                financingQuota2: entry[32],
                commission: entry[18],
                costs: entry[19],
                followProcedure: entry[20],
                financingProcedure: entry[21],
                requiredDocuments: entry[22],
                reimbursementConditions: entry[23],
                agreementEvaluation: entry[24],
                contact: entry[25],
                createdAt: new Date(entry.date_created),
            }));
            return reply.code(200).send(supportOffers);
        }
        catch (_a) {
            return reply.code(200).send([]);
        }
    });
}
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
//---------------------------------------------------------------------------------------
function getCompaniesSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const apiKey = req.params.apiKey;
        if (apiKey !== env_1.wpApiSecret)
            return reply.code(400).send({ message: "Bad api key" });
        const companies = yield prisma_1.default.company.findMany({
            where: { active: true, verified: true },
            include: {
                users: {
                    select: {
                        id: true,
                        firstName: true,
                        lastName: true,
                        position: true,
                    },
                },
                city: true,
                contactPosition: true,
                nEmployees: true,
                turnover: true,
            },
        });
        return reply.code(200).send(companies);
    });
}
//---------------------------------------------------------------------------------------
function getUsersSync(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,
                civility: true,
                firstName: true,
                lastName: true,
                city: true,
                position: true,
                expertiseAreas: true,
                interestAreas: true,
                bio: true,
            },
            orderBy: {
                firstName: "asc",
            },
        });
        return reply.code(200).send(users);
    });
}
//---------------------------------------------------------------------------------------
function getOpportunitiesSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const opportunities = yield prisma_1.default.opportunity.findMany({
            where: {
                AND: [
                    {
                        active: true,
                    },
                    {
                        OR: [
                            {
                                validityDate: null,
                            },
                            {
                                validityDate: {
                                    gte: new Date(),
                                },
                            },
                        ],
                    },
                ],
            },
            include: {
                comments: {
                    orderBy: { createdAt: "asc" },
                    include: {
                        user: {
                            select: {
                                id: true,
                                firstName: true,
                                lastName: true,
                            },
                        },
                    },
                },
                likes: true,
            },
        });
        return reply.code(200).send(opportunities);
    });
}
//---------------------------------------------------------------------------------------
function getAppointmentsSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const appointments = yield prisma_1.default.appointment.findMany({
            orderBy: {
                date: "desc",
            },
            where: {
                active: true,
                activationDate: {
                    lte: new Date(),
                },
                date: {
                    gte: new Date(),
                },
            },
            include: {
                comments: {
                    orderBy: { createdAt: "asc" },
                    include: {
                        user: {
                            select: {
                                id: true,
                                firstName: true,
                                lastName: true,
                            },
                        },
                    },
                },
                likes: true,
            },
        });
        const newAppointments = yield Promise.all(appointments.map((appointment) => __awaiter(this, void 0, void 0, function* () {
            const presignedImages = yield Promise.all(appointment.images.map((image) => __awaiter(this, void 0, void 0, function* () { return yield (0, minio_1.getPresignedUrl)(image); })));
            return Object.assign(Object.assign({}, appointment), { images: presignedImages });
        })));
        return reply.code(200).send(newAppointments);
    });
}
// ------------------------------------------------------------------------------------
function getEventsSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const events = yield prisma_1.default.event.findMany({
            orderBy: {
                date: "desc",
            },
            where: { active: true },
            include: {
                comments: {
                    orderBy: { createdAt: "asc" },
                    include: {
                        user: {
                            select: {
                                id: true,
                                firstName: true,
                                lastName: true,
                            },
                        },
                    },
                },
                likes: true,
            },
        });
        const newEvents = yield Promise.all(events.map((event) => __awaiter(this, void 0, void 0, function* () {
            const presignedImages = yield Promise.all(event.images.map((image) => __awaiter(this, void 0, void 0, function* () { return yield (0, minio_1.getPresignedUrl)(image); })));
            return Object.assign(Object.assign({}, event), { images: presignedImages });
        })));
        return reply.code(200).send(newEvents);
    });
}
// ------------------------------------------------------------------------------------
function getAlbumsSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const albums = yield prisma_1.default.album.findMany({
            orderBy: {
                date: "desc",
            },
        });
        const newAlbums = yield Promise.all(albums.map((album) => __awaiter(this, void 0, void 0, function* () {
            const presignedImages = yield Promise.all(album.images.map((image) => __awaiter(this, void 0, void 0, function* () { return yield (0, minio_1.getPresignedUrl)(image); })));
            return {
                id: album.id,
                title: album.title,
                date: album.date,
                images: presignedImages,
            };
        })));
        return reply.code(200).send(newAlbums);
    });
}
// ------------------------------------------------------------------------------------
function getVideosSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const videos = yield prisma_1.default.video.findMany({
            orderBy: {
                date: "desc",
            },
        });
        return reply.code(200).send(videos);
    });
}
// ------------------------------------------------------------------------------------
function getEditionsSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const editions = yield prisma_1.default.edition.findMany({
            orderBy: {
                title: "asc",
            },
            include: {
                category: true,
            },
        });
        const newEditions = yield Promise.all(editions.map((edition) => __awaiter(this, void 0, void 0, function* () {
            return ({
                id: edition.id,
                title: edition.title,
                categoryId: edition.categoryId,
                category: edition.category,
                document: yield (0, minio_1.getPresignedUrl)(edition.document),
                image: edition.image ? yield (0, minio_1.getPresignedUrl)(edition.image) : null,
            });
        })));
        return reply.code(200).send(newEditions);
    });
}
// ------------------------------------------------------------------------------------
function getTrainingsSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const trainings = yield prisma_1.default.training.findMany({
            orderBy: {
                date: "desc",
            },
        });
        const newTrainings = yield Promise.all(trainings.map((training) => __awaiter(this, void 0, void 0, function* () {
            return Object.assign(Object.assign({}, training), { document: training.document
                    ? yield (0, minio_1.getPresignedUrl)(training.document)
                    : null });
        })));
        return reply.code(200).send(newTrainings);
    });
}
// ------------------------------------------------------------------------------------
function getFairsSync(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const fairs = yield prisma_1.default.fair.findMany({
            orderBy: {
                startDate: "desc",
            },
        });
        return reply.code(200).send(fairs);
    });
}
// ------------------------------------------------------------------------------------
