/**
 * Chat Notifications
 *
 * Sends certification notifications to Slack, Microsoft Teams, and Discord.
 * Supports rich message formatting with findings summaries.
 *
 * @module enterprise/integrations/chat
 */
// ============================================================================
// Slack Client
// ============================================================================
/**
 * Slack webhook client
 */
export class SlackClient {
    webhookUrl;
    constructor(webhookUrl) {
        this.webhookUrl = webhookUrl;
    }
    /**
     * Send certification notification
     */
    async sendNotification(notification) {
        const blocks = this.buildBlocks(notification);
        try {
            const response = await fetch(this.webhookUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ blocks }),
            });
            if (!response.ok) {
                return {
                    success: false,
                    platform: "slack",
                    timestamp: new Date().toISOString(),
                    error: `Slack webhook returned ${response.status}`,
                };
            }
            return {
                success: true,
                platform: "slack",
                timestamp: new Date().toISOString(),
            };
        }
        catch (error) {
            return {
                success: false,
                platform: "slack",
                timestamp: new Date().toISOString(),
                error: error instanceof Error ? error.message : String(error),
            };
        }
    }
    /**
     * Build Slack blocks
     */
    buildBlocks(notification) {
        const blocks = [];
        // Header
        const statusEmoji = this.getStatusEmoji(notification.status, notification.score);
        blocks.push({
            type: "header",
            text: {
                type: "plain_text",
                text: `${statusEmoji} Vaspera Certification: ${notification.status.toUpperCase()}`,
                emoji: true,
            },
        });
        // Context
        blocks.push({
            type: "context",
            elements: [
                {
                    type: "mrkdwn",
                    text: `*Target:* ${notification.target} | *ID:* ${notification.certificationId}`,
                },
            ],
        });
        // Score section (if completed)
        if (notification.status === "completed" && notification.score !== undefined) {
            blocks.push({
                type: "section",
                fields: [
                    {
                        type: "mrkdwn",
                        text: `*Score:* ${notification.score}/100`,
                    },
                    {
                        type: "mrkdwn",
                        text: `*Grade:* ${notification.grade || this.calculateGrade(notification.score)}`,
                    },
                ],
            });
        }
        // Findings summary
        if (notification.findings) {
            const { findings } = notification;
            blocks.push({
                type: "section",
                text: {
                    type: "mrkdwn",
                    text: [
                        "*Findings Summary:*",
                        `🔴 Critical: ${findings.critical}`,
                        `🟠 High: ${findings.high}`,
                        `🟡 Medium: ${findings.medium}`,
                        `🔵 Low: ${findings.low}`,
                        `⚪ Info: ${findings.info}`,
                    ].join("\n"),
                },
            });
            // Top findings
            if (findings.topFindings && findings.topFindings.length > 0) {
                blocks.push({
                    type: "section",
                    text: {
                        type: "mrkdwn",
                        text: "*Top Findings:*\n" +
                            findings.topFindings
                                .map((f) => `• *${f.id}* (${f.severity}): ${f.description.slice(0, 80)}...`)
                                .join("\n"),
                    },
                });
            }
        }
        // Report link
        if (notification.reportUrl) {
            blocks.push({
                type: "actions",
                elements: [
                    {
                        type: "button",
                        text: {
                            type: "plain_text",
                            text: "View Full Report",
                            emoji: true,
                        },
                        url: notification.reportUrl,
                        style: "primary",
                    },
                ],
            });
        }
        // Divider
        blocks.push({ type: "divider" });
        return blocks;
    }
    /**
     * Get status emoji
     */
    getStatusEmoji(status, score) {
        if (status === "started")
            return "🔄";
        if (status === "failed")
            return "❌";
        if (score === undefined)
            return "✅";
        if (score >= 90)
            return "🏆";
        if (score >= 70)
            return "✅";
        if (score >= 50)
            return "⚠️";
        return "❌";
    }
    /**
     * Calculate grade from score
     */
    calculateGrade(score) {
        if (score >= 90)
            return "A";
        if (score >= 80)
            return "B";
        if (score >= 70)
            return "C";
        if (score >= 60)
            return "D";
        return "F";
    }
}
// ============================================================================
// Microsoft Teams Client
// ============================================================================
/**
 * Microsoft Teams webhook client
 */
export class TeamsClient {
    webhookUrl;
    constructor(webhookUrl) {
        this.webhookUrl = webhookUrl;
    }
    /**
     * Send certification notification
     */
    async sendNotification(notification) {
        const card = this.buildAdaptiveCard(notification);
        try {
            const response = await fetch(this.webhookUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({
                    type: "message",
                    attachments: [
                        {
                            contentType: "application/vnd.microsoft.card.adaptive",
                            content: card,
                        },
                    ],
                }),
            });
            if (!response.ok) {
                return {
                    success: false,
                    platform: "teams",
                    timestamp: new Date().toISOString(),
                    error: `Teams webhook returned ${response.status}`,
                };
            }
            return {
                success: true,
                platform: "teams",
                timestamp: new Date().toISOString(),
            };
        }
        catch (error) {
            return {
                success: false,
                platform: "teams",
                timestamp: new Date().toISOString(),
                error: error instanceof Error ? error.message : String(error),
            };
        }
    }
    /**
     * Build Adaptive Card
     */
    buildAdaptiveCard(notification) {
        const statusColor = this.getStatusColor(notification.status, notification.score);
        const body = [
            // Header
            {
                type: "TextBlock",
                size: "Large",
                weight: "Bolder",
                text: `Vaspera Certification: ${notification.status.toUpperCase()}`,
                color: statusColor,
            },
            // Target info
            {
                type: "FactSet",
                facts: [
                    { title: "Target", value: notification.target },
                    { title: "ID", value: notification.certificationId },
                ],
            },
        ];
        // Score
        if (notification.status === "completed" && notification.score !== undefined) {
            body.push({
                type: "FactSet",
                facts: [
                    { title: "Score", value: `${notification.score}/100` },
                    { title: "Grade", value: notification.grade || this.calculateGrade(notification.score) },
                ],
            });
        }
        // Findings
        if (notification.findings) {
            const { findings } = notification;
            body.push({ type: "TextBlock", text: "**Findings Summary**", weight: "Bolder" }, {
                type: "FactSet",
                facts: [
                    { title: "🔴 Critical", value: String(findings.critical) },
                    { title: "🟠 High", value: String(findings.high) },
                    { title: "🟡 Medium", value: String(findings.medium) },
                    { title: "🔵 Low", value: String(findings.low) },
                    { title: "⚪ Info", value: String(findings.info) },
                ],
            });
            // Top findings
            if (findings.topFindings && findings.topFindings.length > 0) {
                body.push({ type: "TextBlock", text: "**Top Findings**", weight: "Bolder" }, ...findings.topFindings.map((f) => ({
                    type: "TextBlock",
                    text: `• **${f.id}** (${f.severity}): ${f.description.slice(0, 80)}...`,
                    wrap: true,
                })));
            }
        }
        // Actions
        const actions = [];
        if (notification.reportUrl) {
            actions.push({
                type: "Action.OpenUrl",
                title: "View Full Report",
                url: notification.reportUrl,
            });
        }
        return {
            $schema: "http://adaptivecards.io/schemas/adaptive-card.json",
            type: "AdaptiveCard",
            version: "1.4",
            body,
            actions: actions.length > 0 ? actions : undefined,
        };
    }
    /**
     * Get status color for Teams
     */
    getStatusColor(status, score) {
        if (status === "started")
            return "Accent";
        if (status === "failed")
            return "Attention";
        if (score === undefined)
            return "Good";
        if (score >= 70)
            return "Good";
        if (score >= 50)
            return "Warning";
        return "Attention";
    }
    /**
     * Calculate grade from score
     */
    calculateGrade(score) {
        if (score >= 90)
            return "A";
        if (score >= 80)
            return "B";
        if (score >= 70)
            return "C";
        if (score >= 60)
            return "D";
        return "F";
    }
}
// ============================================================================
// Discord Client
// ============================================================================
/**
 * Discord webhook client
 */
export class DiscordClient {
    webhookUrl;
    constructor(webhookUrl) {
        this.webhookUrl = webhookUrl;
    }
    /**
     * Send certification notification
     */
    async sendNotification(notification) {
        const embed = this.buildEmbed(notification);
        try {
            const response = await fetch(this.webhookUrl, {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ embeds: [embed] }),
            });
            if (!response.ok) {
                return {
                    success: false,
                    platform: "discord",
                    timestamp: new Date().toISOString(),
                    error: `Discord webhook returned ${response.status}`,
                };
            }
            return {
                success: true,
                platform: "discord",
                timestamp: new Date().toISOString(),
            };
        }
        catch (error) {
            return {
                success: false,
                platform: "discord",
                timestamp: new Date().toISOString(),
                error: error instanceof Error ? error.message : String(error),
            };
        }
    }
    /**
     * Build Discord embed
     */
    buildEmbed(notification) {
        const color = this.getEmbedColor(notification.status, notification.score);
        const fields = [
            { name: "Target", value: notification.target, inline: true },
            { name: "ID", value: notification.certificationId, inline: true },
        ];
        // Score
        if (notification.status === "completed" && notification.score !== undefined) {
            fields.push({ name: "Score", value: `${notification.score}/100`, inline: true }, {
                name: "Grade",
                value: notification.grade || this.calculateGrade(notification.score),
                inline: true,
            });
        }
        // Findings
        if (notification.findings) {
            const { findings } = notification;
            fields.push({
                name: "Findings",
                value: [
                    `🔴 Critical: ${findings.critical}`,
                    `🟠 High: ${findings.high}`,
                    `🟡 Medium: ${findings.medium}`,
                    `🔵 Low: ${findings.low}`,
                    `⚪ Info: ${findings.info}`,
                ].join("\n"),
                inline: false,
            });
            // Top findings
            if (findings.topFindings && findings.topFindings.length > 0) {
                fields.push({
                    name: "Top Findings",
                    value: findings.topFindings
                        .map((f) => `• **${f.id}** (${f.severity}): ${f.description.slice(0, 60)}...`)
                        .join("\n"),
                    inline: false,
                });
            }
        }
        // Report link
        if (notification.reportUrl) {
            fields.push({
                name: "Report",
                value: `[View Full Report](${notification.reportUrl})`,
                inline: false,
            });
        }
        return {
            title: `Vaspera Certification: ${notification.status.toUpperCase()}`,
            color,
            fields,
            timestamp: new Date().toISOString(),
            footer: {
                text: "Vaspera Hardening MCP",
            },
        };
    }
    /**
     * Get embed color (decimal)
     */
    getEmbedColor(status, score) {
        if (status === "started")
            return 0x3498db; // Blue
        if (status === "failed")
            return 0xe74c3c; // Red
        if (score === undefined)
            return 0x2ecc71; // Green
        if (score >= 70)
            return 0x2ecc71; // Green
        if (score >= 50)
            return 0xf39c12; // Orange
        return 0xe74c3c; // Red
    }
    /**
     * Calculate grade from score
     */
    calculateGrade(score) {
        if (score >= 90)
            return "A";
        if (score >= 80)
            return "B";
        if (score >= 70)
            return "C";
        if (score >= 60)
            return "D";
        return "F";
    }
}
// ============================================================================
// Unified Chat Client
// ============================================================================
/**
 * Unified chat notification client
 */
export class ChatClient {
    client;
    platform;
    constructor(config) {
        this.platform = config.platform;
        switch (config.platform) {
            case "slack":
                this.client = new SlackClient(config.webhookUrl);
                break;
            case "teams":
                this.client = new TeamsClient(config.webhookUrl);
                break;
            case "discord":
                this.client = new DiscordClient(config.webhookUrl);
                break;
            default:
                throw new Error(`Unsupported chat platform: ${config.platform}`);
        }
    }
    /**
     * Send certification notification
     */
    async sendNotification(notification) {
        return this.client.sendNotification(notification);
    }
    /**
     * Get platform name
     */
    getPlatform() {
        return this.platform;
    }
}
// ============================================================================
// Multi-Platform Notifier
// ============================================================================
/**
 * Multi-platform notification manager
 */
export class MultiPlatformNotifier {
    clients = [];
    /**
     * Add a chat platform
     */
    addPlatform(config) {
        this.clients.push(new ChatClient(config));
    }
    /**
     * Send notification to all platforms
     */
    async sendNotification(notification) {
        const results = await Promise.all(this.clients.map((client) => client.sendNotification(notification)));
        return results;
    }
    /**
     * Send notification from findings
     */
    async notifyFindings(certificationId, target, findings, score, reportUrl) {
        const summary = this.summarizeFindings(findings);
        const notification = {
            certificationId,
            target,
            status: "completed",
            score,
            grade: this.calculateGrade(score),
            findings: summary,
            reportUrl,
        };
        return this.sendNotification(notification);
    }
    /**
     * Summarize findings
     */
    summarizeFindings(findings) {
        const summary = {
            total: findings.length,
            critical: 0,
            high: 0,
            medium: 0,
            low: 0,
            info: 0,
            topFindings: [],
        };
        for (const f of findings) {
            summary[f.severity]++;
        }
        // Get top 3 findings by severity
        const sorted = [...findings].sort((a, b) => {
            const order = ["critical", "high", "medium", "low", "info"];
            return order.indexOf(a.severity) - order.indexOf(b.severity);
        });
        summary.topFindings = sorted.slice(0, 3).map((f) => ({
            id: f.id,
            severity: f.severity,
            description: f.description,
        }));
        return summary;
    }
    /**
     * Calculate grade from score
     */
    calculateGrade(score) {
        if (score >= 90)
            return "A";
        if (score >= 80)
            return "B";
        if (score >= 70)
            return "C";
        if (score >= 60)
            return "D";
        return "F";
    }
}
// ============================================================================
// Factory Functions
// ============================================================================
/**
 * Create chat client
 */
export function createChatClient(config) {
    return new ChatClient(config);
}
/**
 * Create Slack client
 */
export function createSlackClient(webhookUrl) {
    return new SlackClient(webhookUrl);
}
/**
 * Create Teams client
 */
export function createTeamsClient(webhookUrl) {
    return new TeamsClient(webhookUrl);
}
/**
 * Create Discord client
 */
export function createDiscordClient(webhookUrl) {
    return new DiscordClient(webhookUrl);
}
/**
 * Create multi-platform notifier
 */
export function createMultiPlatformNotifier() {
    return new MultiPlatformNotifier();
}
//# sourceMappingURL=chat.js.map