namespace MyOffice.Data.Repositories.Account;

using Microsoft.EntityFrameworkCore;
using Models.Accounts;
using MyOffice.DbContext;

public class MotionRepository : AppRepository<Motion>, IMotionRepository
{
	public MotionRepository(AppDbContext context) : base(context)
	{
	}

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

	public async Task<List<Motion>> GetByAccountAsync(
		Guid accountId,
		DateTime dateFrom,
		DateTime dateTo,
		CancellationToken cancellationToken = default
	)
	{
		return await _context
			.Motions
			.Include(x => x.Item)
			.ThenInclude(x => x.ItemGlobal)
			.Where(x => x.AccountId == accountId && x.DateTime >= dateFrom && x.DateTime <= dateTo)
			.OrderByDescending(x => x.DateTime)
			.ThenByDescending(x => x.CreatedOn)
			.ToListAsync(cancellationToken);
	}

	public async Task<Motion?> GetAsync(Guid userId, Guid id, CancellationToken cancellationToken = default)
	{
		return await _context
			.Motions
			.Include(x => x.Item)
			.ThenInclude(x => x.ItemGlobal)
			.FirstOrDefaultAsync(
				x => x.Account!.AccessRights!.Any(a => a.UserId == userId) && x.Id == id,
				cancellationToken);
	}

	public async Task<bool> UpdateAsync(Motion motion, CancellationToken cancellationToken = default)
	{
		return await UpdateBaseAsync(motion, cancellationToken) > 0;
	}

	public async Task<bool> RemoveAsync(Motion motion, CancellationToken cancellationToken = default)
	{
		return await RemoveBaseAsync(motion, cancellationToken) > 0;
	}
}
