using FastEndpoints; using Microsoft.EntityFrameworkCore; using PyroFetes.Models; namespace PyroFetes.Endpoints.Product; public class DeleteProductRequest { public int Id { get; set; } } public class DeleteProductEndpoint(PyroFetesDbContext db) : Endpoint { public override void Configure() { Delete("/api/products/{@id}", x => new { x.Id }); AllowAnonymous(); } public override async Task HandleAsync(DeleteProductRequest req, CancellationToken ct) { // Récupérer le produit var productToDelete = await db.Products .SingleOrDefaultAsync(p => p.Id == req.Id, ct); if (productToDelete is null) { Console.WriteLine($"Aucun produit avec l'ID {req.Id} trouvé."); await Send.NotFoundAsync(ct); return; } // Supprimer les liaisons Price var relatedPrices = await db.Prices .Where(p => p.ProductId == req.Id) .ToListAsync(ct); if (relatedPrices.Any()) { db.Prices.RemoveRange(relatedPrices); } // Supprimer les liaisons WarehouseProduct var relatedWarehouseProducts = await db.WarehouseProducts .Where(wp => wp.ProductId == req.Id) .ToListAsync(ct); if (relatedWarehouseProducts.Any()) { db.WarehouseProducts.RemoveRange(relatedWarehouseProducts); } // Supprimer le produit db.Products.Remove(productToDelete); await db.SaveChangesAsync(ct); Console.WriteLine($"Produit {req.Id}, ses prix et ses entrepôts liés ont été supprimés avec succès."); await Send.NoContentAsync(ct); } }