namespace MyOffice.Data.Repositories.Item;

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

public class ItemGlobalRepository : AppRepository<ItemGlobal>, IItemGlobalRepository
{
	public ItemGlobalRepository(AppDbContext context) : base(context)
	{
	}

	public ItemGlobal? Get(Guid id)
	{
		return _context.ItemGlobals.FirstOrDefault(x => x.Id == id);
	}

	public ItemGlobal? GetByName(string name)
	{
		return _context.ItemGlobals.FirstOrDefault(x => x.Name == name);
	}

	public Task<ItemGlobal?> GetByNameAsync(string name, CancellationToken cancellationToken = default)
	{
		return _context.ItemGlobals.FirstOrDefaultAsync(x => x.Name == name, cancellationToken);
	}

	public bool Add(ItemGlobal itemGlobal)
	{
		return AddBase(itemGlobal) > 0;
	}

	public async Task<bool> AddAsync(ItemGlobal itemGlobal, CancellationToken cancellationToken = default)
	{
		return await AddBaseAsync(itemGlobal, cancellationToken) > 0;
	}

	public List<ItemGlobal> GetAvailableToUser(Guid userId)
	{
		return _context.Motions
			.Include(x => x.Item)
			.ThenInclude(x => x.ItemGlobal)
			.ThenInclude(x => x.Items)
			.ThenInclude(x => x.Category)
			.Where(x => x.Account.AccessRights!.Any(a => a.UserId == userId))
			.Where(x => x.Item.ItemGlobal.Items.All(g => g.Category!.UserId != userId))
			.Select(x => x.Item.ItemGlobal)
			.GroupBy(x => x.Id)
			.Select(x => x.First())
			.ToList();
	}

	public async Task<List<ItemGlobal>> GetAvailableToUserAsync(
		Guid userId,
		CancellationToken cancellationToken = default)
	{
		return await _context.Motions
			.Include(x => x.Item)
			.ThenInclude(x => x.ItemGlobal)
			.ThenInclude(x => x.Items)
			.ThenInclude(x => x.Category)
			.Where(x => x.Account.AccessRights!.Any(a => a.UserId == userId))
			.Where(x => x.Item.ItemGlobal.Items.All(g => g.Category!.UserId != userId))
			.Select(x => x.Item.ItemGlobal)
			.GroupBy(x => x.Id)
			.Select(x => x.First())
			.ToListAsync(cancellationToken);
	}
}