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> 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 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 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 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 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 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 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(edgeDto.Condition, true, out var cond) ? cond : FlowAPI.Domain.Enums.EdgeCondition.True }).ToList(); // Calculate deltas for achievements var oldNodes = graph.Nodes ?? new List(); var oldEdges = graph.Edges ?? new List(); 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 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> GetSharedUsersAsync(Guid graphId, Guid ownerId) { var graph = await _repo.GetByIdAsync(graphId); if (graph is null || graph.UserId != ownerId) return Enumerable.Empty(); 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 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 }; } }