"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());
    });
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendCampaign = exports.getCampaigns = void 0;
const client_1 = require("@prisma/client");
const email_1 = require("../../lib/email");
const prisma = new client_1.PrismaClient();
// GET /api/admin/marketing/campaigns
const getCampaigns = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const campaigns = yield prisma.campaign.findMany({
            orderBy: { createdAt: 'desc' },
            take: 20,
        });
        const formattedCampaigns = campaigns.map(c => ({
            id: c.id,
            subject: c.subject,
            audience: c.audience === 'ALL' ? 'All Users' : c.audience,
            sent: c.sentCount,
            opened: "-", // Placeholder for future analytics
            status: c.status,
            date: c.createdAt.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }),
        }));
        res.json(formattedCampaigns);
    }
    catch (error) {
        console.error("Get Campaigns Error:", error);
        res.status(500).json({ error: "Failed to fetch campaigns" });
    }
});
exports.getCampaigns = getCampaigns;
// POST /api/admin/marketing/campaigns/send
const sendCampaign = (req, res) => __awaiter(void 0, void 0, void 0, function* () {
    try {
        const { subject, body, recipient } = req.body;
        if (!subject || !body || !recipient) {
            return res.status(400).json({ error: "Missing required fields" });
        }
        // 1. Determine Audience & Fetch Emails
        let users = [];
        if (recipient === 'all') {
            users = yield prisma.user.findMany({ select: { email: true, fullName: true } });
        }
        else if (recipient === 'newsletter') {
            // Assuming you have a boolean flag or a separate subscription model
            // For now, let's simulate fetching all users
            users = yield prisma.user.findMany({ select: { email: true, fullName: true } });
        }
        // Add logic for VIP/Abandoned here...
        if (users.length === 0) {
            return res.status(400).json({ error: "No recipients found for this audience." });
        }
        // 2. Send Emails in Batches (to avoid memory issues/rate limits)
        // For production, use a Queue (BullMQ/Redis). For this MVP, we use Promise.all.
        const emailPromises = users.map(user => {
            var _a;
            // Personalize content
            const personalizedBody = body.replace('{{name}}', ((_a = user.fullName) === null || _a === void 0 ? void 0 : _a.split(' ')[0]) || 'Customer');
            const personalizedHtml = `<p>${personalizedBody.replace(/\n/g, '<br>')}</p>`; // Simple HTML conversion
            return (0, email_1.sendEmail)({
                to: user.email,
                subject,
                html: personalizedHtml
            });
        });
        yield Promise.all(emailPromises);
        // 3. Create Campaign Record
        const campaign = yield prisma.campaign.create({
            data: {
                subject,
                body,
                audience: recipient.toUpperCase(),
                status: 'SENT',
                sentCount: users.length,
                sentAt: new Date(),
            }
        });
        res.json({ message: "Campaign sent successfully", campaign });
    }
    catch (error) {
        console.error("Send Campaign Error:", error);
        res.status(500).json({ error: "Failed to send campaign" });
    }
});
exports.sendCampaign = sendCampaign;
