using PyroFetes.DTO.Product.Request; using PyroFetes.DTO.Product.Response; using FastEndpoints; using Microsoft.EntityFrameworkCore; using PyroFetes.Models; namespace PyroFetes.Endpoints.Product; // Endpoint permettant de mettre à jour un produit existant public class UpdateProductEndpoint(PyroFetesDbContext db) : Endpoint { public override void Configure() { // Route HTTP PUT avec un paramètre d'identifiant dans l'URL Put("/api/products/{@id}", x => new { x.Id }); // Autorise les requêtes anonymes (sans authentification) AllowAnonymous(); } public override async Task HandleAsync(UpdateProductDto req, CancellationToken ct) { // Recherche du produit à mettre à jour, en incluant les relations Prices et WarehouseProducts var product = await db.Products .Include(p => p.Prices) .Include(p => p.WarehouseProducts) .SingleOrDefaultAsync(p => p.Id == req.Id, ct); // Si le produit n'existe pas, on retourne une réponse 404 if (product is null) { await Send.NotFoundAsync(ct); return; } // Mise à jour des propriétés principales du produit product.Reference = req.References.ToString(); // Converti int → string product.Name = req.Name; product.Duration = req.Duration; product.Caliber = req.Caliber; product.ApprovalNumber = req.ApprovalNumber; product.Weight = req.Weight; product.Nec = req.Nec; product.Image = req.Image; product.Link = req.Link; product.ClassificationId = req.ClassificationId; product.ProductCategoryId = req.ProductCategoryId; // Mise à jour des prix fournisseurs associés db.Prices.RemoveRange(product.Prices); foreach (var s in req.Suppliers) { db.Prices.Add(new Price { ProductId = product.Id, SupplierId = s.SupplierId, SellingPrice = s.SellingPrice }); } // Mise à jour des entrepôts associés db.WarehouseProducts.RemoveRange(product.WarehouseProducts); foreach (var w in req.Warehouses) { db.WarehouseProducts.Add(new WarehouseProduct { ProductId = product.Id, WarehouseId = w.WarehouseId, Quantity = w.Quantity }); } await db.SaveChangesAsync(ct); // Construction de la réponse renvoyée au client var response = new GetProductDto { Id = product.Id, Reference = req.References, // DTO garde int pour cohérence Name = req.Name, Duration = req.Duration, Caliber = req.Caliber, ApprovalNumber = req.ApprovalNumber, Weight = req.Weight, Nec = req.Nec, // Le prix de vente est pris depuis Prices SellingPrice = req.Suppliers.FirstOrDefault()?.SellingPrice ?? 0, Image = req.Image, Link = req.Link, ClassificationId = req.ClassificationId, ProductCategoryId = req.ProductCategoryId, Suppliers = req.Suppliers.Select(s => new ProductSupplierPriceDto { SupplierId = s.SupplierId, SellingPrice = s.SellingPrice }).ToList(), Warehouses = req.Warehouses.Select(w => new GetProductWarehouseDto { WarehouseId = w.WarehouseId, Quantity = w.Quantity, WarehouseName = db.Warehouses .FirstOrDefault(x => x.Id == w.WarehouseId)?.Name ?? string.Empty }).ToList() }; await Send.OkAsync(response, ct); } }