File size: 12,178 Bytes
b9c7f0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
using FlowAPI.Application.DTOs.Graph;
using FlowAPI.Application.Interfaces;
using FlowAPI.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace FlowAPI.Application.Services
{
    public class GraphService : IGraphService
    {
        private readonly IGraphRepository _repo;
        private readonly ITaskNodeRepository _nodeRepo;
        private readonly IEdgeRepository _edgeRepo;
        private readonly IAchievementService _achievementService;
        private readonly ISharedGraphRepository _sharedGraphRepo;
        private readonly IUserRepository _userRepo;

        public GraphService(
            IGraphRepository repo, 
            ITaskNodeRepository nodeRepo, 
            IEdgeRepository edgeRepo, 
            IAchievementService achievementService,
            ISharedGraphRepository sharedGraphRepo,
            IUserRepository userRepo)
        {
            _repo = repo;
            _nodeRepo = nodeRepo;
            _edgeRepo = edgeRepo;
            _achievementService = achievementService;
            _sharedGraphRepo = sharedGraphRepo;
            _userRepo = userRepo;
        }

        public async Task<IEnumerable<GraphResponseDto>> GetAllByUserIdAsync(Guid userId)
        {
            // Owned graphs
            var ownedGraphs = await _repo.GetAllByUserIdAsync(userId);
            var ownedDtos = ownedGraphs.Select(g => 
            {
                var dto = MapToDto(g);
                dto.IsShared = false;
                dto.Permission = "Owner";
                return dto;
            }).ToList();

            // Shared graphs
            var sharedShares = await _sharedGraphRepo.GetSharedGraphsByUserIdAsync(userId);

            var sharedDtos = sharedShares.Select(s => 
            {
                var dto = MapToDto(s.Graph);
                dto.IsShared = true;
                dto.Permission = s.Permission;
                return dto;
            }).ToList();

            return ownedDtos.Concat(sharedDtos);
        }

        public async Task<GraphResponseDto?> GetByIdAsync(Guid id, Guid currentUserId)
        {
            var graph = await _repo.GetByIdAsync(id);
            if (graph is null) return null;

            if (graph.UserId == currentUserId)
            {
                var dto = MapToDto(graph);
                dto.IsShared = false;
                dto.Permission = "Owner";
                return dto;
            }

            var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId);
            if (shared is not null)
            {
                var dto = MapToDto(graph);
                dto.IsShared = true;
                dto.Permission = shared.Permission;
                return dto;
            }

            return null;
        }

        public async Task<FullGraphResponseDto?> GetFullByIdAsync(Guid id, Guid currentUserId)
        {
            var graph = await _repo.GetByIdWithDetailsAsync(id);
            if (graph is null) return null;

            string permission = "Owner";
            bool isShared = false;

            if (graph.UserId != currentUserId)
            {
                var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId);
                if (shared is null) return null;
                permission = shared.Permission;
                isShared = true;
            }

            return new FullGraphResponseDto
            {
                Id = graph.Id,
                UserId = graph.UserId,
                Title = graph.Title,
                Description = graph.Description,
                CreatedAt = graph.CreatedAt,
                IsShared = isShared,
                Permission = permission,
                Nodes = graph.Nodes.Select(n => new NodeDto
                {
                    Id = n.Id,
                    Label = n.Label,
                    PosX = n.PosX,
                    PosY = n.PosY,
                    Type = n.Type,
                    State = (int)n.State,
                    Decision = n.Decision
                }).ToList(),
                Edges = graph.Edges.Select(e => new EdgeDto
                {
                    Id = e.Id,
                    FromNodeId = e.FromNodeId,
                    ToNodeId = e.ToNodeId,
                    Condition = e.Condition.ToString()
                }).ToList()
            };
        }

        public async Task<GraphResponseDto> CreateAsync(CreateGraphDto dto, Guid currentUserId)
        {
            var graph = new Graph
            {
                Id = Guid.NewGuid(),
                UserId = currentUserId, // Secure: always force authenticated user ID
                Title = dto.Title,
                Description = dto.Description,
                CreatedAt = DateTime.UtcNow
            };

            var created = await _repo.CreateAsync(graph);
            
            await _achievementService.ProcessEventAsync(currentUserId, "GraphCreated");
            
            var result = MapToDto(created);
            result.IsShared = false;
            result.Permission = "Owner";
            return result;
        }

        public async Task<GraphResponseDto?> UpdateAsync(Guid id, UpdateGraphDto dto, Guid currentUserId)
        {
            var graph = await _repo.GetByIdAsync(id);
            if (graph is null) return null;

            // Secure: only allowed for owner or edit shared users
            if (graph.UserId != currentUserId)
            {
                var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId);
                if (shared is null || shared.Permission != "Edit") return null;
            }

            if (dto.Title is not null) graph.Title = dto.Title;
            if (dto.Description is not null) graph.Description = dto.Description;

            var updated = await _repo.UpdateAsync(graph);
            var result = MapToDto(updated);
            if (graph.UserId != currentUserId)
            {
                result.IsShared = true;
                result.Permission = "Edit";
            }
            return result;
        }

        public async Task<bool> DeleteAsync(Guid id, Guid currentUserId)
        {
            var graph = await _repo.GetByIdAsync(id);
            if (graph == null) return false;

            // Secure: only owner can delete the graph
            if (graph.UserId != currentUserId) return false;
            
            var deleted = await _repo.DeleteAsync(id);
            if (deleted)
            {
                await _achievementService.ProcessEventAsync(graph.UserId, "GraphDeleted");
            }
            return deleted;
        }

        public async Task<bool> SaveFullGraphAsync(Guid id, FullGraphResponseDto dto, Guid currentUserId)
        {
            var graph = await _repo.GetByIdWithDetailsAsync(id);
            if (graph is null) return false;

            // Secure: only allowed for owner or shared users with Edit permission
            if (graph.UserId != currentUserId)
            {
                var shared = await _sharedGraphRepo.GetShareAsync(id, currentUserId);
                if (shared is null || shared.Permission != "Edit") return false;
            }

            // Map DTOs to Domain Entities
            var mappedNodes = dto.Nodes.Select(nodeDto => new TaskNode
            {
                Id = nodeDto.Id == Guid.Empty ? Guid.NewGuid() : nodeDto.Id,
                GraphId = id,
                Label = nodeDto.Label,
                PosX = nodeDto.PosX,
                PosY = nodeDto.PosY,
                Type = nodeDto.Type,
                Decision = nodeDto.Decision,
                State = (FlowAPI.Domain.Enums.NodeState)nodeDto.State
            }).ToList();

            var mappedEdges = dto.Edges.Select(edgeDto => new Edge
            {
                FromNodeId = edgeDto.FromNodeId,
                ToNodeId = edgeDto.ToNodeId,
                Condition = Enum.TryParse<FlowAPI.Domain.Enums.EdgeCondition>(edgeDto.Condition, true, out var cond) ? cond : FlowAPI.Domain.Enums.EdgeCondition.True
            }).ToList();

            // Calculate deltas for achievements
            var oldNodes = graph.Nodes ?? new List<TaskNode>();
            var oldEdges = graph.Edges ?? new List<Edge>();

            int newlyCreatedNodes = mappedNodes.Count(n => !oldNodes.Any(o => o.Id == n.Id));
            int newlyCreatedEdges = mappedEdges.Count(e => !oldEdges.Any(o => o.Id == e.Id));
            
            int newlyCompletedNodes = mappedNodes.Count(n => 
                n.State == FlowAPI.Domain.Enums.NodeState.Done && 
                (!oldNodes.Any(o => o.Id == n.Id) || oldNodes.First(o => o.Id == n.Id).State != FlowAPI.Domain.Enums.NodeState.Done)
            );

            // Perform robust Upsert
            var success = await _repo.UpsertFullGraphAsync(id, mappedNodes, mappedEdges);
            if (!success) return false;

            // Trigger Achievements based on deltas
            if (newlyCreatedNodes > 0) await _achievementService.ProcessEventAsync(graph.UserId, "NodeCreated", newlyCreatedNodes);
            if (newlyCreatedEdges > 0) await _achievementService.ProcessEventAsync(graph.UserId, "EdgeCreated", newlyCreatedEdges);
            if (newlyCompletedNodes > 0) await _achievementService.ProcessEventAsync(graph.UserId, "TaskCompleted", newlyCompletedNodes);

            return true;
        }

        public async Task<GraphResponseDto?> ShareGraphAsync(Guid graphId, Guid ownerId, ShareGraphRequestDto dto)
        {
            var graph = await _repo.GetByIdAsync(graphId);
            if (graph is null || graph.UserId != ownerId) return null;

            var targetUser = await _userRepo.GetByEmailAsync(dto.Email.ToLower().Trim());
            if (targetUser is null || targetUser.Id == ownerId) return null;

            var existing = await _sharedGraphRepo.GetShareAsync(graphId, targetUser.Id);
            if (existing is not null)
            {
                existing.Permission = dto.Permission;
                await _sharedGraphRepo.UpdateAsync(existing);
            }
            else
            {
                var share = new SharedGraph
                {
                    Id = Guid.NewGuid(),
                    GraphId = graphId,
                    SharedWithUserId = targetUser.Id,
                    Permission = dto.Permission,
                    CreatedAt = DateTime.UtcNow
                };
                await _sharedGraphRepo.CreateAsync(share);
            }

            var res = MapToDto(graph);
            res.IsShared = true;
            res.Permission = dto.Permission;
            return res;
        }

        public async Task<IEnumerable<SharedUserResponseDto>> GetSharedUsersAsync(Guid graphId, Guid ownerId)
        {
            var graph = await _repo.GetByIdAsync(graphId);
            if (graph is null || graph.UserId != ownerId) return Enumerable.Empty<SharedUserResponseDto>();

            var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);

            return shares.Select(s => new SharedUserResponseDto
            {
                Id = s.Id,
                SharedWithUserId = s.SharedWithUserId,
                Email = s.SharedWithUser?.Email ?? string.Empty,
                DisplayName = s.SharedWithUser?.DisplayName ?? string.Empty,
                Permission = s.Permission
            });
        }

        public async Task<bool> RevokeShareAsync(Guid graphId, Guid ownerId, Guid shareId)
        {
            var graph = await _repo.GetByIdAsync(graphId);
            if (graph is null || graph.UserId != ownerId) return false;

            var share = await _sharedGraphRepo.GetByIdAsync(shareId);
            if (share is null || share.GraphId != graphId) return false;

            return await _sharedGraphRepo.DeleteAsync(shareId);
        }

        private static GraphResponseDto MapToDto(Graph graph) => new()
        {
            Id = graph.Id,
            UserId = graph.UserId,
            Title = graph.Title,
            Description = graph.Description,
            CreatedAt = graph.CreatedAt
        };
    }
}