using AutoMapper; using FastEndpoints; using MetaCourse.Api.Data; using MetaCourse.Api.DTOs.Courses; using MetaCourse.Api.Entities; using Microsoft.EntityFrameworkCore; namespace MetaCourse.Api.Endpoints.Courses; public class CreateCourseEndpoint(AppDbContext db, AutoMapper.IMapper mapper) : Endpoint { public override void Configure() { Post("api/courses"); AllowAnonymous(); Summary(s => s.Summary = "Crée un nouveau cours (statut Brouillon par défaut)"); } public override async Task HandleAsync(CreateCourseDto req, CancellationToken ct) { var creatorExists = await db.Users.AnyAsync(u => u.Id == req.CreatorId, ct); if (!creatorExists) { AddError(r => r.CreatorId, "L'utilisateur créateur n'existe pas."); await SendErrorsAsync(404, ct); return; } var course = mapper.Map(req); db.Courses.Add(course); await db.SaveChangesAsync(ct); var created = await db.Courses .Include(c => c.Creator) .Include(c => c.Topics) .FirstAsync(c => c.Id == course.Id, ct); await SendAsync(mapper.Map(created), 201, ct); } }