Files
BeReadyBackend/BeReadyBackend/Endpoints/Groups/DeleteGroupEndpoint.cs
T
2026-03-11 18:41:41 +01:00

48 lines
1.5 KiB
C#

using BeReadyBackend.Models;
using BeReadyBackend.Repositories;
using BeReadyBackend.Services;
using BeReadyBackend.Specifications.Groups;
using BeReadyBackend.Specifications.Users;
using FastEndpoints;
using Group = BeReadyBackend.Models.Group;
namespace BeReadyBackend.Endpoints.Groups;
public class GroupDeletedRequest
{
public int Id { get; set; }
}
public class DeleteGroupEndpoint(GroupsRepository groupsRepository, UserGroupsRepository userGroupsRepository, UserService userService) : Endpoint<GroupDeletedRequest>
{
public override void Configure()
{
Delete("/Groups/{@Id}", x => new { x.Id });
}
public override async Task HandleAsync(GroupDeletedRequest req, CancellationToken ct)
{
int userId = userService.GetUserIdFromToken();
Group? group = await groupsRepository.SingleOrDefaultAsync(new GetGroupByIdSpec(req.Id), ct);
if (group is null)
{
await Send.NotFoundAsync(ct);
return;
}
bool isAdmin = group.UserGroups?.Any(x => x.UserId == userId && x.Grade == "Admin") ?? false;
if (!isAdmin)
{
await Send.StringAsync("Vous n'avez pas les droits pour supprimer ce groupe", 400, cancellation: ct);
return;
}
if (group.UserGroups?.Count > 0)
await userGroupsRepository.DeleteRangeAsync(group.UserGroups, ct);
await groupsRepository.DeleteAsync(group, ct);
await Send.NoContentAsync(ct);
}
}