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f0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
using FlowAPI.Application.DTOs.Graph;
using FlowAPI.Application.Interfaces;
using FlowAPI.Domain.Entities;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
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 => 
                {
                    bool hasLarge = n.Data != null && n.Data.Length > 2000;
                    return new NodeDto
                    {
                        Id = n.Id,
                        Label = n.Label,
                        PosX = n.PosX,
                        PosY = n.PosY,
                        Type = n.Type,
                        State = (int)n.State,
                        Decision = n.Decision,
                        Description = n.Description,
                        Color = n.Color,
                        IsPinned = n.IsPinned,
                        Width = n.Width,
                        Height = n.Height,
                        Data = hasLarge ? null : n.Data,
                        HasLargeData = hasLarge,
                        GroupId = n.GroupId
                    };
                }).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 user = await _userRepo.GetByIdAsync(currentUserId);
            if (user == null) throw new Exception("User not found.");

            if (!Plans.IsPlus(user))
            {
                var ownedGraphsCount = (await _repo.GetAllByUserIdAsync(currentUserId)).Count();
                if (ownedGraphsCount >= Plans.FreeMaxBoards)
                {
                    throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxBoards} boards. Upgrade to Plus for unlimited boards.");
                }
            }

            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");

            if (graph.Nodes.Count > 0)
            {
                await _achievementService.ProcessEventAsync(currentUserId, "NodeCreated", graph.Nodes.Count);
            }
            if (graph.Edges.Count > 0)
            {
                await _achievementService.ProcessEventAsync(currentUserId, "EdgeCreated", graph.Edges.Count);
            }
            
            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;

            var user = await _userRepo.GetByIdAsync(currentUserId);
            if (user == null) throw new Exception("User not found.");

            // 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;
            }

            // Limits are bound to the board owner's plan, not to the editor's
            var owner = graph.UserId == currentUserId ? user : await _userRepo.GetByIdAsync(graph.UserId);
            if (owner != null && !Plans.IsPlus(owner) && dto.Nodes.Count > Plans.FreeMaxNodesPerBoard)
            {
                throw new InvalidOperationException($"Free plan is limited to {Plans.FreeMaxNodesPerBoard} nodes per board. Upgrade to Plus for unlimited nodes.");
            }

            // 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,
                Description = nodeDto.Description,
                Color = nodeDto.Color,
                IsPinned = nodeDto.IsPinned,
                Width = nodeDto.Width,
                Height = nodeDto.Height,
                Data = nodeDto.Data,
                GroupId = nodeDto.GroupId
            }).ToList();

            var mappedEdges = dto.Edges.Select(edgeDto => new Edge
            {
                Id = edgeDto.Id == Guid.Empty ? Guid.NewGuid() : edgeDto.Id,
                GraphId = id,
                FromNodeId = edgeDto.FromNodeId,
                ToNodeId = edgeDto.ToNodeId,
                Condition = edgeDto.Condition ?? "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 owner = await _userRepo.GetByIdAsync(ownerId);
            if (owner == null) throw new Exception("Owner user not found.");

            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
            {
                // Enforce sharing tier limits based on owner's tier
                var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);
                int currentSharedCount = shares?.Count() ?? 0;

                if (!Plans.IsPlus(owner) && currentSharedCount >= Plans.FreeMaxGuestsPerBoard)
                {
                    throw new InvalidOperationException($"Free plan allows up to {Plans.FreeMaxGuestsPerBoard} guests per board. Upgrade to Plus for unlimited collaborators.");
                }

                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) return Enumerable.Empty<SharedUserResponseDto>();

            // Allow access to shares list if caller is the owner or a guest with access
            if (graph.UserId != ownerId)
            {
                var shareAccess = await _sharedGraphRepo.GetShareAsync(graphId, ownerId);
                if (shareAccess is null) return Enumerable.Empty<SharedUserResponseDto>();
            }

            var result = new List<SharedUserResponseDto>();

            // Get owner details
            var owner = await _userRepo.GetByIdAsync(graph.UserId);
            if (owner is not null)
            {
                result.Add(new SharedUserResponseDto
                {
                    Id = Guid.Empty,
                    SharedWithUserId = owner.Id,
                    Email = owner.Email,
                    DisplayName = owner.DisplayName,
                    Permission = "Owner"
                });
            }

            // Get shared users
            var shares = await _sharedGraphRepo.GetSharesForGraphAsync(graphId);
            if (shares is not null)
            {
                result.AddRange(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
                }));
            }

            return result;
        }

        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
        };
    }
}