| 1 | using System.Text.Json; |
| 2 | using System.Text.Json.Nodes; |
| 3 | using CascadeIDE.Models.AgentChat; |
| 4 | using CascadeIDE.Services.Intercom; |
| 5 | |
| 6 | namespace CascadeIDE.Features.Intercom.Transport; |
| 7 | |
| 8 | /// <summary>Добавляет wire extensions к payload перед POST (сохраняет локальный JSON без изменений).</summary> |
| 9 | internal static class IntercomTransportPayloadEnricher |
| 10 | { |
| 11 | public static JsonElement EnrichForWire(string localKind, JsonElement payload, string? operatorMemberId = null) |
| 12 | { |
| 13 | if (!string.IsNullOrWhiteSpace(operatorMemberId)) |
| 14 | { |
| 15 | var withOperator = JsonNode.Parse(payload.GetRawText()) as JsonObject ?? new JsonObject(); |
| 16 | withOperator["operator_member_id"] = operatorMemberId.Trim(); |
| 17 | payload = JsonSerializer.SerializeToElement(withOperator, IntercomTransportJson.Web); |
| 18 | } |
| 19 | |
| 20 | if (!string.Equals(localKind, ChatHistoryEventKind.MessageRangeRelated, StringComparison.Ordinal)) |
| 21 | return payload; |
| 22 | |
| 23 | ChatHistoryMessageRangeRelatedPayload? range; |
| 24 | try |
| 25 | { |
| 26 | range = payload.Deserialize<ChatHistoryMessageRangeRelatedPayload>(IntercomTransportJson.Web); |
| 27 | } |
| 28 | catch (JsonException) |
| 29 | { |
| 30 | return payload; |
| 31 | } |
| 32 | |
| 33 | if (range is null) |
| 34 | return payload; |
| 35 | |
| 36 | var root = JsonNode.Parse(payload.GetRawText()) as JsonObject ?? new JsonObject(); |
| 37 | var relates = root["relates_to"] as JsonArray ?? new JsonArray(); |
| 38 | foreach (var link in IntercomRelatesToWire.FromMessageRangeRelated(range)) |
| 39 | { |
| 40 | var linkJson = JsonSerializer.SerializeToNode(link, IntercomTransportJson.Web); |
| 41 | if (linkJson is not null) |
| 42 | relates.Add(linkJson); |
| 43 | } |
| 44 | |
| 45 | if (relates.Count > 0) |
| 46 | root["relates_to"] = relates; |
| 47 | |
| 48 | if (IntercomMessageRangeRelatedSupport.IsDisjoint(range) |
| 49 | && range.OrdinalSegments is { Count: > 0 } segments) |
| 50 | { |
| 51 | root["ordinal_segments"] = JsonSerializer.SerializeToNode(segments, IntercomTransportJson.Web); |
| 52 | } |
| 53 | |
| 54 | return JsonSerializer.SerializeToElement(root, IntercomTransportJson.Web); |
| 55 | } |
| 56 | } |
| 57 | |