using FastEndpoints; using MetaCourse.Api.Data; using MetaCourse.Api.Entities; using Microsoft.EntityFrameworkCore; namespace MetaCourse.Api.Endpoints.Topics; public class LinkResourceRequest { public Guid TopicId { get; set; } public Guid ResourceId { get; set; } public int Position { get; set; } = 1; } public class LinkResourceToTopicEndpoint(AppDbContext db) : Endpoint { public override void Configure() { Post("api/topics/{topicId}/resources/{resourceId}"); AllowAnonymous(); Summary(s => s.Summary = "Associe une ressource à un sujet"); } public override async Task HandleAsync(LinkResourceRequest req, CancellationToken ct) { var topicExists = await db.Topics.AnyAsync(t => t.Id == req.TopicId, ct); if (!topicExists) { AddError("Le sujet n'existe pas."); await SendErrorsAsync(404, ct); return; } var resourceExists = await db.Resources.AnyAsync(r => r.Id == req.ResourceId, ct); if (!resourceExists) { AddError("La ressource n'existe pas."); await SendErrorsAsync(404, ct); return; } var alreadyLinked = await db.TopicResources .AnyAsync(tr => tr.TopicId == req.TopicId && tr.ResourceId == req.ResourceId, ct); if (alreadyLinked) { AddError("Cette ressource est déjà associée à ce sujet."); await SendErrorsAsync(409, ct); return; } db.TopicResources.Add(new TopicResource { TopicId = req.TopicId, ResourceId = req.ResourceId, Position = req.Position }); await db.SaveChangesAsync(ct); await SendNoContentAsync(ct); } }