using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Weifer.Database.EF; using Weifer.Database.EF.Entitys; using Weifer.ShoppingApp.API.Models; namespace Weifer.ShoppingApp.API.RestApi { [ApiController] [Route("api/[controller]")] public class ShoppingItemApiController : ControllerBase { public readonly DatabaseContext dbContext; public ShoppingItemApiController(DatabaseContext dbContext) { this.dbContext = dbContext; } [HttpGet("getItems")] public async Task GetMainItems([FromQuery] string customerId) { if (!Guid.TryParse(customerId, out var guidCustomerId)) { return BadRequest("Invalid Customer ID"); } var shoppingItems = await dbContext.ShoppingLists .Where(x => x.CustomerId == guidCustomerId && x.ShoppingListName == "MainList") .Include(x => x.ShoppingItems) .SelectMany(x => x.ShoppingItems) // Wählt nur die ShoppingItems aus .ToListAsync(); return Ok(shoppingItems); } [HttpPost("addMainItem")] public async Task AddMainItem([FromBody] AddItemRequest request) { if (!Guid.TryParse(request.CustomerId, out var guidCustomerId)) { return BadRequest("Invalid Customer ID"); } var itemToAdd = new ShoppingItem { ShoppingItemId = new Guid(request.ShoppingItemId), ShoppingListId = await dbContext.ShoppingLists .Where(x => x.CustomerId == guidCustomerId && x.ShoppingListName == "MainList") .Select(x => x.ShoppingListId) .FirstOrDefaultAsync(), Description = request.ItemName, Number = 1, Purchased = false, }; dbContext.ShoppingItems.Add(itemToAdd); await dbContext.SaveChangesAsync(); return Ok(); } [HttpDelete("removeItem/{shoppingItemId}")] public async Task RemoveItem(string shoppingItemId) { if (!Guid.TryParse(shoppingItemId, out Guid guidShoppingItemId)) { return BadRequest("Invalid GUID format for Shopping Item ID"); } var item = dbContext.ShoppingItems.FirstOrDefault(item => item.ShoppingItemId == guidShoppingItemId); if (item == null) { return NotFound("Item not found"); } dbContext.ShoppingItems.Remove(item); await dbContext.SaveChangesAsync(); return Ok(new { message = "Item removed" }); } } public class AddItemRequest { public string CustomerId { get; set; } public string ItemName { get; set; } public string ShoppingItemId { get; set; } } }