using System; using System.Collections.Generic; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using StellaOps.DependencyInjection; using StellaOps.Notify.Engine; using StellaOps.Notify.Models; namespace StellaOps.Notify.Connectors.Slack; [ServiceBinding(typeof(INotifyChannelTestProvider), ServiceLifetime.Singleton)] public sealed class SlackChannelTestProvider : INotifyChannelTestProvider { private static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web); private static readonly string DefaultTitle = "Stella Ops Notify Preview"; public NotifyChannelType ChannelType => NotifyChannelType.Slack; public Task BuildPreviewAsync(ChannelTestPreviewContext context, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); var title = !string.IsNullOrWhiteSpace(context.Request.Title) ? context.Request.Title! : DefaultTitle; var summary = !string.IsNullOrWhiteSpace(context.Request.Summary) ? context.Request.Summary! : $"Preview generated for Slack destination at {context.Timestamp:O}."; var bodyText = !string.IsNullOrWhiteSpace(context.Request.Body) ? context.Request.Body! : summary; var workspace = context.Channel.Config.Properties.TryGetValue("workspace", out var workspaceName) ? workspaceName : null; var contextElements = new List { new { type = "mrkdwn", text = $"Preview generated {context.Timestamp:O} ยท Trace `{context.TraceId}`" } }; if (!string.IsNullOrWhiteSpace(workspace)) { contextElements.Add(new { type = "mrkdwn", text = $"Workspace: `{workspace}`" }); } var payload = new { channel = context.Target, text = $"{title}\n{bodyText}", blocks = new object[] { new { type = "section", text = new { type = "mrkdwn", text = $"*{title}*\n{bodyText}" } }, new { type = "context", elements = contextElements.ToArray() } } }; var body = JsonSerializer.Serialize(payload, JsonOptions); var preview = NotifyDeliveryRendered.Create( NotifyChannelType.Slack, NotifyDeliveryFormat.Slack, context.Target, title, body, summary, context.Request.TextBody ?? bodyText, context.Request.Locale, ChannelTestPreviewUtilities.ComputeBodyHash(body), context.Request.Attachments); var metadata = SlackMetadataBuilder.Build(context); return Task.FromResult(new ChannelTestPreviewResult(preview, metadata)); } }