pet-companion-back/Repositories/PetInventoryRepository.cs

68 lines
2.1 KiB
C#

using Microsoft.EntityFrameworkCore;
using PetCompanion.Data;
using PetCompanion.Models;
namespace PetCompanion.Repositories
{
public class PetInventoryRepository
{
private readonly ApplicationDbContext _context;
public PetInventoryRepository(ApplicationDbContext context)
{
_context = context;
}
public async Task<Inventory> GetPetInventory(string petId)
{
return await _context.Inventories
.Include(i => i.Items)
.ThenInclude(ii => ii.GameItem)
.FirstOrDefaultAsync(i => i.PetId == petId);
}
public async Task<Dictionary<ItemEquipTarget, int>> GetEquippedItems(string petId)
{
var equippedItems = await _context.EquippedItems
.Where(e => e.PetId == petId)
.ToDictionaryAsync(e => e.EquipTarget, e => e.GameItemId);
return equippedItems;
}
public async Task SaveInventory(Inventory inventory)
{
var existingInventory = await _context.Inventories
.Include(i => i.Items)
.FirstOrDefaultAsync(i => i.PetId == inventory.PetId);
if (existingInventory == null)
{
_context.Inventories.Add(inventory);
}
else
{
// Clear existing items
_context.InventoryItems.RemoveRange(existingInventory.Items);
// Update inventory properties
// existingInventory.Capacity = inventory.Capacity;
// Add new items
foreach (var item in inventory.Items)
{
existingInventory.Items.Add(new InventoryItem
{
InventoryId = existingInventory.PetId,
GameItemId = item.GameItemId,
Quantity = item.Quantity,
GameItem = item.GameItem
});
}
}
await _context.SaveChangesAsync();
}
}
}