using Microsoft.EntityFrameworkCore; using System; using System.Linq; using System.Threading.Tasks; using Webshop.Application; using Webshop.Application.DTOs.Customers; // <--- DIESE ZEILE HAT GEFEHLT (für CartDto) using Webshop.Application.DTOs.Shipping; // (für CartItemDto) using Webshop.Application.Services.Customers.Interfaces; using Webshop.Domain.Entities; using Webshop.Infrastructure.Data; namespace Webshop.Application.Services.Customers { public class CartService : ICartService { private readonly ApplicationDbContext _context; public CartService(ApplicationDbContext context) { _context = context; } // Die Implementierung muss exakt so aussehen: public async Task> GetCartAsync(string userId) { var cart = await GetCartEntity(userId); // Wenn kein Warenkorb da ist, geben wir einen leeren zurück (Success) if (cart == null) { return ServiceResult.Ok(new CartDto { UserId = userId }); } var dto = new CartDto { Id = cart.Id, UserId = userId, Items = cart.Items.Select(i => new CartItemDto { ProductId = i.ProductId, ProductVariantId = i.ProductVariantId, Quantity = i.Quantity }).ToList() }; return ServiceResult.Ok(dto); } public async Task AddToCartAsync(string userId, CartItemDto itemDto) { var cart = await GetCartEntity(userId); if (cart == null) { cart = new Cart { UserId = userId, Id = Guid.NewGuid() }; _context.Carts.Add(cart); } var existingItem = cart.Items.FirstOrDefault(i => i.ProductId == itemDto.ProductId && i.ProductVariantId == itemDto.ProductVariantId); if (existingItem != null) { existingItem.Quantity += itemDto.Quantity; } else { var newItem = new CartItem { CartId = cart.Id, ProductId = itemDto.ProductId, ProductVariantId = itemDto.ProductVariantId, Quantity = itemDto.Quantity }; // WICHTIG: Zur Collection hinzufügen UND dem Context Bescheid geben cart.Items.Add(newItem); _context.CartItems.Add(newItem); } cart.LastModified = DateTime.UtcNow; await _context.SaveChangesAsync(); return ServiceResult.Ok(); } public async Task RemoveFromCartAsync(string userId, Guid productId) { var cart = await GetCartEntity(userId); if (cart == null) return ServiceResult.Fail(ServiceResultType.NotFound, "Warenkorb leer."); var item = cart.Items.FirstOrDefault(i => i.ProductId == productId); if (item != null) { _context.CartItems.Remove(item); await _context.SaveChangesAsync(); } return ServiceResult.Ok(); } public async Task ClearCartAsync(string userId) { var cart = await GetCartEntity(userId); if (cart != null && cart.Items.Any()) { _context.CartItems.RemoveRange(cart.Items); await _context.SaveChangesAsync(); } } private async Task GetCartEntity(string userId) { return await _context.Carts .Include(c => c.Items) .FirstOrDefaultAsync(c => c.UserId == userId); } } }