using Heimdall.Application.Common; using Heimdall.Application.DTOs; using Heimdall.Domain.Entities; using MediatR; using Microsoft.EntityFrameworkCore; namespace Heimdall.Application.Groups.Commands.CreateGroup; public record CreateGroupCommand(string Name, string? Description, Guid? ActorId = null) : IRequest>; public class CreateGroupCommandHandler : IRequestHandler> { private readonly IApplicationDbContext _db; public CreateGroupCommandHandler(IApplicationDbContext db) => _db = db; public async Task> Handle(CreateGroupCommand request, CancellationToken ct) { var exists = await _db.Groups.AnyAsync(g => g.Name == request.Name, ct).ConfigureAwait(false); if (exists) return ServiceResult.Conflict("A group with this name already exists"); var group = new Group(request.Name, request.Description); _db.Groups.Add(group); _db.AuditLogs.Add(new AuditLog(request.ActorId, "Group.Created", "Group", group.Id.ToString(), newValue: System.Text.Json.JsonSerializer.Serialize(new { group.Name, group.Description }))); await _db.SaveChangesWithRetryAsync(ct: ct).ConfigureAwait(false); return ServiceResult.Success(Map(group, 0)); } private static GroupResponse Map(Group g, int userCount) => new( g.Id, g.Name, g.Description, userCount, g.CreatedAt, g.UpdatedAt); }