/**
 * sinks/slack/index.ts
 *
 * Slack notification sink — posts formatted score change messages to
 * configured Slack channels via incoming webhooks.
 *
 * By default, only posts when regressions are detected (avoids notification
 * fatigue). Set `alwaysPost: true` to receive all reports.
 *
 * @see docs/design-docs/report-store/sink-architecture.md
 * @see docs/design-docs/report-store/notifications.md
 */
import { formatRegressionAlert, formatScoreSummary, } from "./format.js";
export class SlackSink {
    webhookUrl;
    channel;
    options;
    name = "slack";
    constructor(webhookUrl, channel, options = {}) {
        this.webhookUrl = webhookUrl;
        this.channel = channel;
        this.options = options;
    }
    healthCheck() {
        try {
            const url = new URL(this.webhookUrl);
            if (url.protocol !== "https:") {
                return Promise.resolve({
                    healthy: false,
                    reason: `Webhook URL must use HTTPS, got ${url.protocol}`,
                });
            }
            if (!this.webhookUrl.startsWith("https://hooks.slack.com/")) {
                // Non-standard URL — warn but don't fail (could be a proxy)
                return Promise.resolve({ healthy: true });
            }
            return Promise.resolve({ healthy: true });
        }
        catch {
            return Promise.resolve({
                healthy: false,
                reason: `Invalid webhook URL: ${this.webhookUrl}`,
            });
        }
    }
    async publish(report) {
        const hasRegressions = report.comparison !== undefined && report.comparison.regressed.length > 0;
        let message;
        if (hasRegressions) {
            message = formatRegressionAlert(report);
        }
        else if (this.options.alwaysPost) {
            message = formatScoreSummary(report);
        }
        else {
            return { reason: "No regressions detected", status: "skipped" };
        }
        const body = { ...message };
        if (this.channel) {
            body.channel = this.channel;
        }
        const response = await fetch(this.webhookUrl, {
            body: JSON.stringify(body),
            headers: { "Content-Type": "application/json" },
            method: "POST",
        });
        if (!response.ok) {
            return {
                error: `Slack webhook returned HTTP ${response.status}`,
                status: "failed",
            };
        }
        return {
            detail: hasRegressions ? "regression alert" : "score summary",
            status: "success",
        };
    }
}
