namespace MyOffice.Data.Repositories.Item;

using Microsoft.EntityFrameworkCore;
using MyOffice.Data.Models.Items;

public class ItemRepository : AppRepository<Item>, IItemRepository
{
	public List<Item> GetAll(Guid userId)
	{
		return _context.Items
			.Include(x => x.Motions)
			.Include(x => x.Category)
			.Include(x => x.ItemGlobal)
			.Where(x => x.Category!.UserId == userId)
			.ToList();
	}

	public List<Item> GetByCategory(Guid userId, Guid categoryId)
	{
		return _context.Items
			.Include(x => x.Motions)
			.Include(x => x.Category)
			.Include(x => x.ItemGlobal)
			.Where(x => x.Category!.UserId == userId && x.CategoryId == categoryId)
			.ToList();
	}

	public Item? GetByGlobal(Guid userId, Guid globalMotionId)
	{
		return _context.Items
			.Include(x => x.Motions)
			.Include(x => x.Category)
			.Include(x => x.ItemGlobal)
			.FirstOrDefault(x => x.Category!.UserId == userId && x.ItemGlobalId == globalMotionId);
	}

	public bool Update(Item item)
	{
		return base.UpdateBase(item) > 0;
	}

	public bool Add(Item item)
	{
		return base.AddBase(item) > 0;
	}

	public List<Item> Find(Guid userId, string term, int limit)
	{
		return _context
			.Items
			.Include(x => x.ItemGlobal)
			.Where(x => x.Category!.UserId == userId && x.ItemGlobal.Name.ToLower().Contains(term.ToLower()))
			.OrderByDescending(x => x!.Motions!.Count())
			.Take(limit)
			.ToList();
	}
}