"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.sendNewsletterCampaign = exports.deleteSubscriber = exports.toggleSubscription = exports.getSubscribers = exports.subscribeNewsletter = void 0;
const database_1 = __importDefault(require("../config/database"));
const response_utils_1 = require("../utils/response.utils");
const logger_1 = require("../config/logger");
// 1. Public subscribe
const subscribeNewsletter = async (req, res) => {
    try {
        const { email, name } = req.body;
        const existing = await database_1.default.newsletterSubscriber.findUnique({
            where: { email: email.toLowerCase() },
        });
        if (existing) {
            if (existing.isActive) {
                return (0, response_utils_1.sendSuccess)(res, 'You are already subscribed to our newsletter list.', { subscriber: existing });
            }
            const updated = await database_1.default.newsletterSubscriber.update({
                where: { email: email.toLowerCase() },
                data: { isActive: true },
            });
            return (0, response_utils_1.sendSuccess)(res, 'Resubscribed successfully!', { subscriber: updated });
        }
        const subscriber = await database_1.default.newsletterSubscriber.create({
            data: {
                email: email.toLowerCase(),
                name,
                isActive: true,
            },
        });
        logger_1.logger.info(`New newsletter subscriber: ${email}`);
        // Mock Mailchimp & SendGrid subscriber list sync
        await syncToMailchimp(email, name);
        await syncToSendGrid(email);
        return (0, response_utils_1.sendSuccess)(res, 'Subscribed to newsletter list successfully!', { subscriber });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to subscribe to newsletter list', error.message, 500);
    }
};
exports.subscribeNewsletter = subscribeNewsletter;
// 2. Admin: List subscribers
const getSubscribers = async (req, res) => {
    try {
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        const subscribers = await database_1.default.newsletterSubscriber.findMany({
            orderBy: { createdAt: 'desc' },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Newsletter subscribers list retrieved', { subscribers });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to fetch subscribers list', error.message, 500);
    }
};
exports.getSubscribers = getSubscribers;
// 3. Admin: Toggle subscription state / unsubscribe
const toggleSubscription = async (req, res) => {
    try {
        const { id } = req.params;
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        const subscriber = await database_1.default.newsletterSubscriber.findUnique({ where: { id } });
        if (!subscriber)
            return (0, response_utils_1.sendError)(res, 'Subscriber not found', null, 404);
        const updated = await database_1.default.newsletterSubscriber.update({
            where: { id },
            data: { isActive: !subscriber.isActive },
        });
        return (0, response_utils_1.sendSuccess)(res, `Subscription status updated successfully to ${updated.isActive ? 'Active' : 'Inactive'}`);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Toggle failed', error.message, 500);
    }
};
exports.toggleSubscription = toggleSubscription;
// 4. Admin: Delete subscriber
const deleteSubscriber = async (req, res) => {
    try {
        const { id } = req.params;
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        await database_1.default.newsletterSubscriber.delete({ where: { id } });
        return (0, response_utils_1.sendSuccess)(res, 'Subscriber deleted from registry database');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Deletion failed', error.message, 500);
    }
};
exports.deleteSubscriber = deleteSubscriber;
// 5. Admin: Send Newsletter Campaign Campaign
const sendNewsletterCampaign = async (req, res) => {
    try {
        const { subject, htmlContent } = req.body;
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Forbidden', null, 403);
        }
        const subscribers = await database_1.default.newsletterSubscriber.findMany({
            where: { isActive: true },
        });
        logger_1.logger.info(`Dispatching newsletter campaign: '${subject}' to ${subscribers.length} active readers.`);
        // Mock Mailchimp & SendGrid API campaigns trigger
        return (0, response_utils_1.sendSuccess)(res, `Newsletter campaign successfully scheduled for delivery to ${subscribers.length} subscribers.`);
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to dispatch newsletter campaign', error.message, 500);
    }
};
exports.sendNewsletterCampaign = sendNewsletterCampaign;
// MOCK MARKETING INTEGRATIONS
async function syncToMailchimp(email, name) {
    logger_1.logger.info(`[Mailchimp API] Synced contact: ${email} (${name || 'Subscriber'}) to audience list ID: 'ibw_readers'`);
}
async function syncToSendGrid(email) {
    logger_1.logger.info(`[SendGrid Marketing Campaigns] Added contact: ${email} to contact list ID: 'ibw_newsletters'`);
}
//# sourceMappingURL=newsletter.controller.js.map