Files
Knots/Knots/Endpoints/Discussion/CreateGroupDiscussionEndpoint.cs
T
2026-06-11 10:33:02 +02:00

91 lines
2.6 KiB
C#

using FastEndpoints;
using Knots.DTO.Discussion;
using Knots.Models;
using Microsoft.EntityFrameworkCore;
using System.Security.Claims;
using Knots.Services;
namespace Knots.Endpoints.Discussion;
public class CreateGroupDiscussionEndpoint(KnotsDbContext db, EncryptionService encryption) : Endpoint<CreateGroupDiscussionRequest, GetDiscussionDto>
{
public override void Configure()
{
Post("/discussions/group");
}
public override async Task HandleAsync(CreateGroupDiscussionRequest req, CancellationToken ct)
{
int currentUserId = int.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier)!);
if (req.Usernames == null || req.Usernames.Count == 0)
{
await SendErrorsAsync(400, ct);
return;
}
List<Models.User> targets = await db.Users
.Where(u => req.Usernames.Contains(u.Username!))
.ToListAsync(ct);
if (targets.Count != req.Usernames.Count)
{
await SendNotFoundAsync(ct);
return;
}
if (targets.Any(t => t.Id == currentUserId))
{
await SendErrorsAsync(400, ct);
return;
}
int totalMembers = targets.Count + 1;
Models.Discussion discussion = new()
{
IsGroup = true,
Key = new Models.Key { EnKey = encryption.GenerateKey() },
UserDiscussions = targets
.Select(t => new UserDiscussion { UserId = t.Id })
.Append(new UserDiscussion { UserId = currentUserId })
.ToList()
};
db.Discussions.Add(discussion);
await db.SaveChangesAsync(ct); // discussion.Id disponible
Models.Group group = new()
{
Name = req.GroupName,
MembersAmount = totalMembers,
DiscussionId = discussion.Id,
GroupUsers = targets
.Select(t => new GroupUser { UserId = t.Id })
.Append(new GroupUser { UserId = currentUserId })
.ToList()
};
db.Groups.Add(group);
await db.SaveChangesAsync(ct); // group.Id disponible
discussion.GroupId = group.Id;
await db.SaveChangesAsync(ct);
await SendOkAsync(new GetDiscussionDto
{
Id = discussion.Id,
IsGroup = true,
Name = group.Name,
MembersCount = totalMembers
}, ct);
}
}
public class CreateGroupDiscussionRequest
{
public string GroupName { get; set; } = "";
public List<string> Usernames { get; set; } = [];
}