"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.AlertsController = void 0;
const logger_1 = require("../../logger");
const alertsService_1 = require("../services/alertsService");
const constants_1 = require("../../constants");
const activityLogService_1 = require("../services/activityLogService");
class AlertsController {
    // Dashboard methods
    static async getDashboardSummaryGraph(req, res) {
        try {
            const { type, startDate, endDate, orgId, projectId } = req.query;
            const result = await AlertsController.alertsService.getDashboardSummaryGraph({
                type: type,
                startDate: startDate,
                endDate: endDate,
                orgId: orgId,
                projectId: projectId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting dashboard summary graph: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get dashboard summary graph',
            });
        }
    }
    static async getSummary(req, res) {
        try {
            const { type, startDate, endDate, orgId, projectId } = req.query;
            const result = await AlertsController.alertsService.getSummary({
                type: type,
                startDate: startDate,
                endDate: endDate,
                orgId: orgId,
                projectId: projectId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting summary: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get summary',
            });
        }
    }
    static async getIncidents(req, res) {
        try {
            const { type, startDate, endDate, orgId, projectId, page, limit } = req.query;
            const result = await AlertsController.alertsService.getIncidents({
                type: type,
                startDate: startDate,
                endDate: endDate,
                orgId: orgId,
                projectId: projectId,
                page: page ? Number.parseInt(page) : 1,
                limit: limit ? Number.parseInt(limit) : 10,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting incidents: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get incidents',
            });
        }
    }
    // Conditions methods
    static async getConditions(req, res) {
        try {
            const { orgId, projectId, page, limit } = req.query;
            const result = await AlertsController.alertsService.getConditions({
                orgId: orgId,
                projectId: projectId,
                page: page ? Number.parseInt(page) : 1,
                limit: limit ? Number.parseInt(limit) : 10,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting conditions: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get conditions',
            });
        }
    }
    static async getConditionDetails(req, res) {
        try {
            const { alertId } = req.params;
            const { orgId, projectId } = req.query;
            const result = await AlertsController.alertsService.getConditionDetails({
                alertId,
                orgId: orgId,
                projectId: projectId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting condition details: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get condition details',
            });
        }
    }
    // Notification channels methods
    static async getNotificationChannels(req, res) {
        try {
            const { orgId, projectId, page, limit } = req.query;
            const result = await AlertsController.alertsService.getNotificationChannels({
                orgId: orgId,
                projectId: projectId,
                page: page ? Number.parseInt(page) : 1,
                limit: limit ? Number.parseInt(limit) : 10,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting notification channels: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get notification channels',
            });
        }
    }
    static async getNotificationChannelDetails(req, res) {
        try {
            const { notificationChannelId } = req.params;
            const { orgId, projectId } = req.query;
            const result = await AlertsController.alertsService.getNotificationChannelDetails({
                notificationChannelId,
                orgId: orgId,
                projectId: projectId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting notification channel details: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get notification channel details',
            });
        }
    }
    static async createNotificationChannel(req, res) {
        try {
            const { name, type, emails = '', webhookConfig = {}, projectId, orgId } = req.body;
            const result = await AlertsController.alertsService.createNotificationChannel({
                name,
                type,
                emails,
                webhookConfig,
                projectId,
                orgId,
            });
            // Log activity
            try {
                const token = req.headers['x-access-token'] || req.headers.authorization;
                const { userId, userName } = (0, activityLogService_1.getUserInfo)(req);
                const [orgName, projectName] = await Promise.all([
                    (0, activityLogService_1.fetchOrgName)(token, orgId),
                    (0, activityLogService_1.fetchProjectName)(token, orgId, projectId),
                ]);
                await (0, activityLogService_1.logActivity)(token, {
                    type: constants_1.ActivityType.CREATE_NOTIFICATION_CHANNEL,
                    params: (0, activityLogService_1.buildActivityParams)({
                        notification_channel_name: { value: name, _id: result?.id },
                        user_name: { value: userName, _id: userId },
                        org_name: { value: orgName || orgId, _id: orgId },
                        project_name: { value: projectName || projectId, _id: projectId },
                    }),
                    project_id: projectId,
                    org_id: orgId,
                    created_by: userId,
                    updated_by: userId,
                });
            }
            catch (activityError) {
                logger_1.logger.error(`Error logging activity for create notification channel: ${activityError}`);
            }
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(error?.message);
            res.status(500).json({
                success: false,
                error: error?.message,
            });
        }
    }
    // Alerts methods
    static async getNotificationChannelAlerts(req, res) {
        try {
            const { projectId, page, limit } = req.query;
            const { notificationChannelId } = req.params;
            const result = await AlertsController.alertsService.getNotificationChannelAlerts({
                projectId: projectId,
                page: page ? Number.parseInt(page) : 1,
                limit: limit ? Number.parseInt(limit) : 10,
                notificationChannelId: notificationChannelId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting alerts: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get alerts',
            });
        }
    }
    static async createAlert(req, res) {
        try {
            const { name, applicationId, alert, notificationChannel, projectId, orgId } = req.body;
            const token = req.headers['x-access-token'] || req.headers.authorization;
            const { userId, userName } = (0, activityLogService_1.getUserInfo)(req);
            const [orgName, projectName] = await Promise.all([
                (0, activityLogService_1.fetchOrgName)(token, orgId),
                (0, activityLogService_1.fetchProjectName)(token, orgId, projectId),
            ]);
            const result = await AlertsController.alertsService.createAlert({
                name,
                applicationId,
                alert,
                notificationChannel,
                projectId,
                workspaceId: orgId,
                projectName,
            });
            // Log activity
            try {
                await (0, activityLogService_1.logActivity)(token, {
                    type: constants_1.ActivityType.CREATE_ALERT_CONDITION,
                    params: (0, activityLogService_1.buildActivityParams)({
                        alert_condition_name: { value: name, _id: result?.id },
                        user_name: { value: userName, _id: userId },
                        org_name: { value: orgName || orgId, _id: orgId },
                        project_name: { value: projectName || projectId, _id: projectId },
                    }),
                    project_id: projectId,
                    org_id: orgId,
                    created_by: userId,
                    updated_by: userId,
                });
            }
            catch (activityError) {
                logger_1.logger.error(`Error logging activity for create alert: ${activityError}`);
            }
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error creating alert: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to create alert',
            });
        }
    }
    static async getAlertIncidents(req, res) {
        try {
            const { projectId, page, limit } = req.query;
            const { alertId } = req.params;
            const result = await AlertsController.alertsService.getAlertIncidents({
                projectId: projectId,
                page: page ? Number.parseInt(page) : 1,
                limit: limit ? Number.parseInt(limit) : 10,
                alertId: alertId,
            });
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error getting alert incidents: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to get alert incidents',
            });
        }
    }
    static async updateAlert(req, res) {
        try {
            const { alertId } = req.params;
            const { name, applicationId, alert, projectId, orgId } = req.body;
            const result = await AlertsController.alertsService.updateAlert({
                alertId,
                name,
                applicationId,
                alert,
                projectId,
                workspaceId: orgId,
            });
            // Log activity
            try {
                const token = req.headers['x-access-token'] || req.headers.authorization;
                const { userId, userName } = (0, activityLogService_1.getUserInfo)(req);
                const [orgName, projectName] = await Promise.all([
                    (0, activityLogService_1.fetchOrgName)(token, orgId),
                    (0, activityLogService_1.fetchProjectName)(token, orgId, projectId),
                ]);
                await (0, activityLogService_1.logActivity)(token, {
                    type: constants_1.ActivityType.UPDATE_ALERT_CONDITION,
                    params: (0, activityLogService_1.buildActivityParams)({
                        alert_condition_name: { value: name || alertId, _id: alertId },
                        user_name: { value: userName, _id: userId },
                        org_name: { value: orgName || orgId, _id: orgId },
                        project_name: { value: projectName || projectId, _id: projectId },
                    }),
                    project_id: projectId,
                    org_id: orgId,
                    created_by: userId,
                    updated_by: userId,
                });
            }
            catch (activityError) {
                logger_1.logger.error(`Error logging activity for update alert: ${activityError}`);
            }
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error updating alert: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to update alert',
            });
        }
    }
    static async updateNotificationChannel(req, res) {
        try {
            const { notificationChannelId } = req.params;
            const { name, type, emails, webhookConfig, projectId, orgId } = req.body;
            const result = await AlertsController.alertsService.updateNotificationChannel({
                notificationChannelId,
                name,
                type,
                emails,
                webhookConfig,
                projectId,
                orgId,
            });
            // Log activity
            try {
                const token = req.headers['x-access-token'] || req.headers.authorization;
                const { userId, userName } = (0, activityLogService_1.getUserInfo)(req);
                const [orgName, projectName] = await Promise.all([
                    (0, activityLogService_1.fetchOrgName)(token, orgId),
                    (0, activityLogService_1.fetchProjectName)(token, orgId, projectId),
                ]);
                await (0, activityLogService_1.logActivity)(token, {
                    type: constants_1.ActivityType.UPDATE_NOTIFICATION_CHANNEL,
                    params: (0, activityLogService_1.buildActivityParams)({
                        notification_channel_name: { value: name || notificationChannelId, _id: notificationChannelId },
                        user_name: { value: userName, _id: userId },
                        org_name: { value: orgName || orgId, _id: orgId },
                        project_name: { value: projectName || projectId, _id: projectId },
                    }),
                    project_id: projectId,
                    org_id: orgId,
                    created_by: userId,
                    updated_by: userId,
                });
            }
            catch (activityError) {
                logger_1.logger.error(`Error logging activity for update notification channel: ${activityError}`);
            }
            res.json({
                success: true,
                data: result,
            });
        }
        catch (error) {
            logger_1.logger.error(`Error updating notification channel: ${error}`);
            res.status(500).json({
                success: false,
                error: 'Failed to update notification channel',
            });
        }
    }
}
exports.AlertsController = AlertsController;
AlertsController.alertsService = new alertsService_1.AlertsService();
//# sourceMappingURL=alerts.js.map