using AutoMapper; using FastEndpoints; using MetaCourse.Api.Data; using MetaCourse.Api.DTOs.UserCourses; using MetaCourse.Api.Entities; using Microsoft.EntityFrameworkCore; namespace MetaCourse.Api.Endpoints.UserCourses; public class EnrollEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint { public override void Configure() { Post("api/courses/{courseId}/enroll"); AllowAnonymous(); Summary(s => s.Summary = "Inscrit un utilisateur à un cours publié"); } public override async Task HandleAsync(EnrollDto req, CancellationToken ct) { var course = await db.Courses.FirstOrDefaultAsync(c => c.Id == req.CourseId, ct); if (course is null) { AddError("Le cours n'existe pas."); await SendErrorsAsync(404, ct); return; } if (course.Status != CourseStatus.Published) { AddError("Impossible de s'inscrire à un cours non publié."); await SendErrorsAsync(422, ct); return; } var userExists = await db.Users.AnyAsync(u => u.Id == req.UserId, ct); if (!userExists) { AddError("L'utilisateur n'existe pas."); await SendErrorsAsync(404, ct); return; } var alreadyEnrolled = await db.UserCourses .AnyAsync(uc => uc.UserId == req.UserId && uc.CourseId == req.CourseId, ct); if (alreadyEnrolled) { AddError("L'utilisateur est déjà inscrit à ce cours."); await SendErrorsAsync(409, ct); return; } var enrollment = new UserCourse { UserId = req.UserId, CourseId = req.CourseId }; db.UserCourses.Add(enrollment); await db.SaveChangesAsync(ct); var result = await db.UserCourses .Include(uc => uc.Course) .FirstAsync(uc => uc.UserId == req.UserId && uc.CourseId == req.CourseId, ct); await SendAsync(mapper.Map(result), 201, ct); } }