"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.getUsers = getUsers;
exports.sendEmail = sendEmail;
exports.sendNotification = sendNotification;
exports.sendSms = sendSms;
exports.getUser = getUser;
exports.editUserActive = editUserActive;
exports.editUserMember = editUserMember;
const client_1 = require("@prisma/client");
const mail_1 = require("../../utils/mail");
const prisma_1 = __importDefault(require("../../utils/prisma"));
const smsGateway_1 = require("../../services/smsGateway");
// -------------------------------------------------------------------------
function getUsers(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const users = yield prisma_1.default.user.findMany({
            where: {
                role: client_1.$Enums.Role.User,
            },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                phoneNumber: true,
                active: true,
                member: true,
                position: true,
                createdAt: true,
            },
            orderBy: {
                createdAt: "desc",
            },
        });
        return reply.code(200).send(users);
    });
}
// -------------------------------------------------------------------------
function sendEmail(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        console.log('📧 ============ DÉBUT ENVOI EMAIL ============');
        console.log('📋 Données reçues:', JSON.stringify(data, null, 2));
        console.log('👤 IDs utilisateurs cibles:', data.users);
        const users = yield prisma_1.default.user.findMany({
            where: {
                id: { in: data.users },
                role: client_1.$Enums.Role.User,
            },
            select: {
                id: true,
                email: true,
                firstName: true,
                lastName: true
            },
        });
        console.log('👥 UTILISATEURS TROUVÉS:', JSON.stringify(users, null, 2));
        console.log('🔢 Nombre d\'utilisateurs:', users.length);
        // Vérification de la configuration Mailgun
        console.log('🔧 CONFIG MAILGUN:');
        console.log('   - Domain: ccis-agadir.com');
        console.log('   - API Key présent:', !!process.env.MAILGUN_API_KEY);
        console.log('   - Expéditeur configuré: "CCIS Souss Massa <noreply@ccis-agadir.com>"');
        // Vérification de la configuration Nodemailer (ancien système)
        console.log('🔧 CONFIG NODEMAILER:');
        console.log('   - Host:', process.env.EMAIL_HOST);
        console.log('   - User:', process.env.EMAIL_HOST_USER);
        console.log('   - Expéditeur actuel:', process.env.EMAIL_HOST_USER);
        let results = {
            total: users.length,
            success: 0,
            failed: 0,
            details: []
        };
        yield Promise.all(users.map((user) => __awaiter(this, void 0, void 0, function* () {
            var _a;
            console.log(`\n🔄 TENTATIVE ENVOI À: ${user.email}`);
            console.log(`   👤 ${user.firstName} ${user.lastName} (ID: ${user.id})`);
            try {
                // TEST avec Mailgun
                console.log('   📤 Utilisation de MAILGUN...');
                const mailgunData = {
                    from: "CCIS Souss Massa <ccisa@ccis-agadir.com>",
                    to: user.email,
                    subject: data.subject,
                    html: data.body,
                    'h:Reply-To': 'ccisa@ccis-agadir.com'
                };
                console.log('   📨 DONNÉES MAILGUN:', JSON.stringify(mailgunData, null, 2));
                ////////        const result = await mg.messages.create('ccis-agadir.com', mailgunData);
                console.log(`   ✅ MAILGUN SUCCÈS pour ${user.email}`);
                console.log('   📦 Réponse Mailgun:', JSON.stringify(results, null, 2));
                results.success++;
                results.details.push({
                    userId: user.id,
                    email: user.email,
                    status: 'success',
                    service: 'mailgun',
                    messageId: ((_a = results.details[0]) === null || _a === void 0 ? void 0 : _a.id) || "unknown"
                });
            }
            catch (mailgunError) {
                console.error(`   ❌ MAILGUN ÉCHEC pour ${user.email}:`, mailgunError.message);
                console.error('   📌 Stack:', mailgunError.stack);
                // Fallback vers Nodemailer si Mailgun échoue
                try {
                    console.log('   🔄 Tentative avec NODEMAILER (fallback)...');
                    const mailOptions = {
                        from: `"CCIS Souss Massa" <${process.env.EMAIL_HOST_USER}>`,
                        to: user.email,
                        subject: data.subject,
                        html: data.body,
                    };
                    console.log('   📨 DONNÉES NODEMAILER:', JSON.stringify(mailOptions, null, 2));
                    const nodemailerResult = yield mail_1.mail.sendMail(mailOptions);
                    console.log(`   ✅ NODEMAILER SUCCÈS pour ${user.email}`);
                    console.log('   📦 Réponse Nodemailer:', JSON.stringify(nodemailerResult, null, 2));
                    results.success++;
                    results.details.push({
                        userId: user.id,
                        email: user.email,
                        status: 'success',
                        service: 'nodemailer',
                        messageId: nodemailerResult.messageId
                    });
                }
                catch (nodemailerError) {
                    console.error(`   ❌ NODEMAILER ÉCHEC pour ${user.email}:`, nodemailerError.message);
                    results.failed++;
                    results.details.push({
                        userId: user.id,
                        email: user.email,
                        status: 'failed',
                        service: 'both',
                        error: nodemailerError.message
                    });
                }
            }
        })));
        console.log('\n📊 ============ RÉSULTATS FINAUX ============');
        console.log(`✅ Succès: ${results.success}`);
        console.log(`❌ Échecs: ${results.failed}`);
        console.log(`📊 Total: ${results.total}`);
        console.log('🔍 Détails:', JSON.stringify(results.details, null, 2));
        console.log('📧 ============ FIN ENVOI EMAIL ============\n');
        return reply.code(200).send({
            message: `Emails envoyés: ${results.success} succès, ${results.failed} échecs`,
            results: results
        });
    });
}
// -------------------------------------------------------------------------
function sendNotification(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        const users = yield prisma_1.default.user.findMany({
            where: {
                id: { in: data.users },
                role: client_1.$Enums.Role.User,
            },
            select: { id: true },
        });
        yield Promise.all(users.map((user) => __awaiter(this, void 0, void 0, function* () {
            yield prisma_1.default.notification.create({
                data: {
                    title: "Message de l'administration",
                    content: data.content,
                    userId: user.id,
                    source: client_1.$Enums.Source.Administration,
                },
            });
        })));
        return reply.code(200).send({});
    });
}
// -------------------------------------------------------------------------
function sendSms(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const data = req.body;
        const users = yield prisma_1.default.user.findMany({
            where: {
                id: { in: data.users },
                role: client_1.$Enums.Role.User,
            },
            select: { id: true, phoneNumber: true },
        });
        if (users.length === 0) {
            return reply.code(400).send({ message: "Aucun utilisateur valide" });
        }
        const results = yield Promise.all(users.map((u) => __awaiter(this, void 0, void 0, function* () {
            const recipient = u.phoneNumber.startsWith("+212")
                ? u.phoneNumber.replace("+", "")
                : (u.phoneNumber.startsWith("0") ? "212" + u.phoneNumber.slice(1) : u.phoneNumber);
            const res = yield (0, smsGateway_1.sendSmsAuto)({
                recipient,
                content: data.content,
                senderId: process.env.SMS_SENDER_ID, // override possible
                userId: u.id
            });
            return { userId: u.id, recipient, ok: res.ok === true };
        })));
        const okCount = results.filter(r => r.ok).length;
        const koCount = results.length - okCount;
        return reply.code(200).send({
            message: `SMS envoyés: ${okCount} succès, ${koCount} échec(s).`,
            details: results
        });
    });
}
// -------------------------------------------------------------------------
function getUser(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const user = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.User,
            },
            select: {
                id: true,
                civility: true,
                firstName: true,
                lastName: true,
                email: true,
                city: true,
                position: true,
                phoneNumber: true,
                expertiseAreas: true,
                interestAreas: true,
                bio: true,
                company: {
                    select: {
                        id: true,
                        name: true,
                    },
                },
                active: true,
                member: true,
                createdAt: true,
            },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        return reply.code(200).send(user);
    });
}
// -------------------------------------------------------------------------
function editUserActive(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const data = req.body;
        const user = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.User,
            },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const newUser = yield prisma_1.default.user.update({
            where: { id: id },
            data: {
                active: data.active,
            },
        });
        return reply
            .code(200)
            .send({ active: newUser.active, companyId: newUser.companyId });
    });
}
// -------------------------------------------------------------------------
function editUserMember(req, reply) {
    return __awaiter(this, void 0, void 0, function* () {
        const id = req.params.id;
        const data = req.body;
        const user = yield prisma_1.default.user.findUnique({
            where: {
                id: id,
                role: client_1.$Enums.Role.User,
            },
        });
        if (!user) {
            return reply.code(404).send({
                message: "Cet utilisateur n'existe pas",
            });
        }
        const newUser = yield prisma_1.default.user.update({
            where: { id: id },
            data: {
                member: data.member,
            },
        });
        return reply
            .code(200)
            .send({ member: newUser.member, companyId: newUser.companyId });
    });
}
// -------------------------------------------------------------------------
