namespace MyOffice.Data.Repositories.Account;

using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging;
using Models.Accounts;
using MyOffice.Data.Models.Accounts.Domain;
using MyOffice.Data.Models.Currencies;
using MyOffice.Data.Repositories;
using MyOffice.DbContext;

public class AccountRepository : AppRepository<Account>, IAccountRepository
{
	private readonly ILogger<AccountRepository> _logger;

	public AccountRepository(
		AppDbContext context,
		ILogger<AccountRepository> logger
	) : base(context)
	{
		_logger = logger;
	}

	public List<Account> GetAll(Guid userId)
	{
		return _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			// categories created with current user
			.Include(x => x.Categories!.Where(c => c.Category.UserId == userId))!
			.ThenInclude(x => x.Category)
			// access rights created with current user
			.Include(x => x.AccessRights!.Where(a => a.OwnerId == userId))!
			.ThenInclude(x => x.User)
			// require only one motions to check if can to delete account
			.Include(x => x.Motions!.Take(1))!
			// only accounts with access to current user
			.Where(x => x.AccessRights!.Any(a => a.UserId == userId))
			.ToList();
	}

	public async Task<List<Account>> GetAllAsync(Guid userId, CancellationToken cancellationToken = default)
	{
		return await _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			// categories created with current user
			.Include(x => x.Categories!.Where(c => c.Category.UserId == userId))!
			.ThenInclude(x => x.Category)
			// access rights created with current user
			.Include(x => x.AccessRights!.Where(a => a.OwnerId == userId))!
			.ThenInclude(x => x.User)
			// require only one motions to check if can to delete account
			.Include(x => x.Motions!.Take(1))!
			// only accounts with access to current user
			.Where(x => x.AccessRights!.Any(a => a.UserId == userId))
			.ToListAsync(cancellationToken);
	}

	public List<Account> GetByCategory(Guid userId, Guid categoryId)
	{
		return _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			.Include(x => x.Categories)!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.Include(x => x.Motions)!
			.Where(x => x.Categories!.Any(c => c.CategoryId == categoryId) && x.AccessRights!.Any(a => a.UserId == userId))
			.ToList();
	}

	public async Task<List<Account>> GetByCategoryAsync(Guid userId, Guid categoryId, CancellationToken cancellationToken = default)
	{
		return await _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			.Include(x => x.Categories)!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.Include(x => x.Motions)!
			.Where(x => x.Categories!.Any(c => c.CategoryId == categoryId) && x.AccessRights!.Any(a => a.UserId == userId))
			.ToListAsync(cancellationToken);
	}

	public List<AccountDetailed> GetByCategoryDetailed(Guid userId, Guid categoryId)
	{
		return _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			.Include(x => x.Categories)!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.Where(x => x.Categories!.Any(c => c.CategoryId == categoryId) && x.AccessRights!.Any(a => a.UserId == userId))
			.Select(x => new AccountDetailed
			{
				Account = x,
				TotalPlus = x.Motions!.Sum(m => m.AmountPlus),
				TotalMinus = x.Motions!.Sum(m => m.AmountMinus),
			})
			.ToList();
	}

	public Task<List<AccountDetailed>> GetByCategoryDetailedAsync(
		Guid userId,
		Guid categoryId,
		CancellationToken cancellationToken = default
	)
	{
		return _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			.Include(x => x.Categories)!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.Where(x => x.Categories!.Any(c => c.CategoryId == categoryId) && x.AccessRights!.Any(a => a.UserId == userId))
			.Select(x => new AccountDetailed
			{
				Account = x,
				TotalPlus = x.Motions!.Sum(m => m.AmountPlus),
				TotalMinus = x.Motions!.Sum(m => m.AmountMinus),
			})
			.ToListAsync(cancellationToken);
	}

	public AccountDetailed? GetByIdDetailed(Guid userId, Guid id)
	{
		return _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			.Include(x => x.Categories)!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.Where(x => x.Id == id && x.AccessRights!.Any(a => a.UserId == userId))
			.Select(x => new AccountDetailed
			{
				Account = x,
				TotalPlus = x.Motions!.Sum(m => m.AmountPlus),
				TotalMinus = x.Motions!.Sum(m => m.AmountMinus),
			})
			.FirstOrDefault();
	}

	public Task<AccountDetailed?> GetByIdDetailedAsync(
		Guid userId,
		Guid id,
		CancellationToken cancellationToken = default
	)
	{
		return _context.Accounts!
			.Include(x => x.CurrencyGlobal)
			.Include(x => x.Categories)!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.Where(x => x.Id == id && x.AccessRights!.Any(a => a.UserId == userId))
			.Select(x => new AccountDetailed
			{
				Account = x,
				TotalPlus = x.Motions!.Sum(m => m.AmountPlus),
				TotalMinus = x.Motions!.Sum(m => m.AmountMinus),
			})
			.FirstOrDefaultAsync(cancellationToken);
	}

	public bool Add(Account account)
	{
		return AddBase(account) > 0;
	}

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

	public bool Delete(Account account)
	{
		return RemoveBase(account) > 0;
	}

	public async Task<bool> DeleteAsync(Account account, CancellationToken cancellationToken = default)
	{
		return await RemoveBaseAsync(account, cancellationToken) > 0;
	}

	public Account? Get(Guid userId, Guid id)
	{
		return _context.Accounts!
			.Include(x => x.Categories!.Where(c => c.Category.UserId == userId))!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			//.Include(x => x.Motions)!
			.FirstOrDefault(x => x.Id == id && x.AccessRights!.Any(r => r.UserId == userId));
	}

	public Task<Account?> GetAsync(Guid userId, Guid id, CancellationToken cancellationToken = default)
	{
		return _context.Accounts!
			.Include(x => x.Categories!.Where(c => c.Category.UserId == userId))!
			.ThenInclude(x => x.Category)
			.Include(x => x.AccessRights)!
			.ThenInclude(x => x.User)
			.FirstOrDefaultAsync(
				x => x.Id == id && x.AccessRights!.Any(r => r.UserId == userId),
				cancellationToken);
	}

	public bool Update(Account account)
	{
		return UpdateBase(account) > 0;
	}

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

	public bool Remove(Account account)
	{
		return RemoveBase(account) > 0;
	}

	public List<Account> FindAccounts(Guid userId, string term)
	{
		return _context.Accounts
			.Where(x => x.AccessRights!.Any(a => a.UserId == userId))
			.Where(x => x.Name.ToLower().Contains(term.ToLower()))
			.ToList();
	}

	public async Task<List<Account>> FindAccountsAsync(Guid userId, string term, CancellationToken cancellationToken = default)
	{
		return await _context.Accounts
			.Where(x => x.AccessRights!.Any(a => a.UserId == userId))
			.Where(x => x.Name.ToLower().Contains(term.ToLower()))
			.ToListAsync(cancellationToken);
	}

	public List<AccountWithRate> GetAccountsWithRate(Guid userId, DateTime date)
	{
		var accounts = _context.Accounts
			.Where(x => x.AccessRights!.Any(a => a.UserId == userId))
			.ToList();

		var currencyIds = accounts
			.Select(x => x.CurrencyGlobalId)
			.ToList();

		var rates = _context.CurrencyRates
			.Include(x => x.Currency)
			.Where(x => x.Currency!.UserId == userId)
			.Where(x => x.DateTime <= date)
			.Where(x => currencyIds.Contains(x.Currency!.CurrencyGlobalId))
			.GroupBy(x => x.Currency!.CurrencyGlobalId)
			.Select(x => x.OrderByDescending(r => r.DateTime).First())
			.ToList();

		return accounts
			.Select(account =>
			{
				var rate = rates.FirstOrDefault(rate => rate.Currency!.CurrencyGlobalId == account.CurrencyGlobalId);

				var result = new AccountWithRate
				{
					Account = account,
					Currency = rate?.Currency,
					Rate = rate,
				};

				return result;
			})
			.ToList(); 
	}

	public List<AccountSimple> GetRestAtDate(Guid userId, DateTime date)
	{
		return _context.AccountAccesses!
			.Where(x => x.UserId == userId)
			.Include(x => x.Account!)
			.ThenInclude(x => x.CurrencyGlobal!)
			.ThenInclude(x => x.Currencies!)
			.ThenInclude(x => x.CurrentRate!)
			.Include(x => x.Account)
			.ThenInclude(x => x!.Motions)
			.Select(x => new 
			{
				Id = x.AccountId,
				Name = x.Account!.Name,
				Type = x.Type,
				Currency = x.Account!.CurrencyGlobal!.Currencies!.FirstOrDefault(c => c.UserId == userId),
				CurrentRate = x.Account!.CurrencyGlobal!.Currencies!.FirstOrDefault(c => c.UserId == userId)!.CurrentRate,
				Plus = x.Account.Motions!
					.Where(x => !x.DeletedOn.HasValue)
					.Sum(m => m.AmountPlus),
				Minus = x.Account.Motions!
					.Where(x => !x.DeletedOn.HasValue)
					.Sum(m => m.AmountMinus),
			})
			.ToList()
			.Select(x => new AccountSimple
			{
				Id = x.Id,
				Name = x.Name,
				Type = x.Type,
				CurrencyName = x.Currency?.Name,
				CurrencyShortName = x.Currency?.ShortName,
				CurrencyRate = x.CurrentRate?.Rate,
				CurrencyQuantity = x.CurrentRate?.Quantity,
				TotalMinus = x.Minus,
				TotalPlus = x.Plus,
				Balance = x.Plus - x.Minus,
			})
			.ToList();
	}

	public List<MotionTotalSimple> GetIncomeByCategories(Guid userId, DateTime from, DateTime to)
	{
		var accounts = GetAccountsWithRate(userId, to);
		var accountIds = accounts.Select(x => x.Account.Id);

		return _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => accountIds.Contains(x.AccountId))
			.Where(x => !x.Item.Category!.IsInternal)
			.GroupBy(x => new
			{
				Id = x.Item.CategoryId,
				Name = x.Item.Category!.Name,
				IsUserCategory = x.Item.Category!.UserId == userId,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.ToList()
			.Select(x => new MotionTotalSimple
			{
				Id = x.Key.IsUserCategory ? x.Key.Id : userId,
				Name = x.Key.Name,
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Amount = x.Sum(a => a.AmountPlus),
			})
			.ToList();
	}

	public List<MotionTotalSimple> GetIncomeByCategory(Guid userId, Guid categoryId, DateTime from, DateTime to)
	{
		return _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => x.Item.Category!.UserId == userId)
			.Where(x => x.Item.CategoryId == categoryId)
			.Where(x => !x.Item.Category!.IsInternal)
			.Where(x => x.Item.Category!.UserId == userId)
			.GroupBy(x => new
			{
				Id = x.Item.ItemGlobalId,
				Name = x.Item.ItemGlobal!.Name,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.Select(x => new MotionTotalSimple
			{
				Name = x.Key.Name,
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Amount = x.Sum(a => a.AmountPlus),
			})
			.ToList();
	}


	public List<MotionTotalSimple> GetOutcomeByCategories(Guid userId, DateTime from, DateTime to)
	{
		var accounts = GetAccountsWithRate(userId, to);
		var accountIds = accounts.Select(x => x.Account.Id);

		return _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => accountIds.Contains(x.AccountId))
			.Where(x => !x.Item.Category!.IsInternal)
			.GroupBy(x => new
			{
				Id = x.Item.CategoryId,
				Name = x.Item.Category!.Name,
				IsUserCategory = x.Item.Category!.UserId == userId,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.Select(x => new MotionTotalSimple
			{
				Id = x.Key.IsUserCategory ? x.Key.Id : userId,
				Name = x.Key.IsUserCategory ? x.Key.Name : "UnCategorized",
				//Name = x.Key.Name,
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Amount = x.Sum(a => a.AmountMinus),
			}).ToList();
	}


	public List<MotionTotalSimple> GetOutcomeByCategory(Guid userId, Guid categoryId, DateTime from, DateTime to)
	{
		var accounts = GetAccountsWithRate(userId, to);
		var accountIds = accounts.Select(x => x.Account.Id);

		return _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => accountIds.Contains(x.AccountId))
			.Where(x => !x.Item.Category!.IsInternal)
			.Where(x => x.Item.CategoryId == categoryId)
			.GroupBy(x => new
			{
				Id = x.Item.ItemGlobalId,
				Name = x.Item.ItemGlobal!.Name,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.Select(x => new MotionTotalSimple
			{
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Name = x.Key.Name,
				Amount = x.Sum(a => a.AmountMinus),
			})
			.ToList();
	}

	public async Task<List<AccountWithRate>> GetAccountsWithRateAsync(
		Guid userId,
		DateTime date,
		CancellationToken cancellationToken = default
	)
	{
		var accounts = await _context.Accounts
			.Where(x => x.AccessRights!.Any(a => a.UserId == userId))
			.ToListAsync(cancellationToken);

		var currencyIds = accounts
			.Select(x => x.CurrencyGlobalId)
			.ToList();

		var rates = await _context.CurrencyRates
			.Include(x => x.Currency)
			.Where(x => x.Currency!.UserId == userId)
			.Where(x => x.DateTime <= date)
			.Where(x => currencyIds.Contains(x.Currency!.CurrencyGlobalId))
			.GroupBy(x => x.Currency!.CurrencyGlobalId)
			.Select(x => x.OrderByDescending(r => r.DateTime).First())
			.ToListAsync(cancellationToken);

		return accounts
			.Select(account =>
			{
				var rate = rates.FirstOrDefault(r => r.Currency!.CurrencyGlobalId == account.CurrencyGlobalId);
				return new AccountWithRate
				{
					Account = account,
					Currency = rate?.Currency,
					Rate = rate,
				};
			})
			.ToList();
	}

	public async Task<List<AccountSimple>> GetRestAtDateAsync(
		Guid userId,
		DateTime date,
		CancellationToken cancellationToken = default
	)
	{
		var rows = await _context.AccountAccesses!
			.Where(x => x.UserId == userId)
			.Include(x => x.Account!)
			.ThenInclude(x => x.CurrencyGlobal!)
			.ThenInclude(x => x.Currencies!)
			.ThenInclude(x => x.CurrentRate!)
			.Include(x => x.Account)
			.ThenInclude(x => x!.Motions)
			.Select(x => new
			{
				Id = x.AccountId,
				Name = x.Account!.Name,
				Type = x.Type,
				Currency = x.Account!.CurrencyGlobal!.Currencies!.FirstOrDefault(c => c.UserId == userId),
				CurrentRate = x.Account!.CurrencyGlobal!.Currencies!.FirstOrDefault(c => c.UserId == userId)!.CurrentRate,
				Plus = x.Account.Motions!
					.Where(m => !m.DeletedOn.HasValue)
					.Sum(m => m.AmountPlus),
				Minus = x.Account.Motions!
					.Where(m => !m.DeletedOn.HasValue)
					.Sum(m => m.AmountMinus),
			})
			.ToListAsync(cancellationToken);

		return rows
			.Select(x => new AccountSimple
			{
				Id = x.Id,
				Name = x.Name,
				Type = x.Type,
				CurrencyName = x.Currency?.Name,
				CurrencyShortName = x.Currency?.ShortName,
				CurrencyRate = x.CurrentRate?.Rate,
				CurrencyQuantity = x.CurrentRate?.Quantity,
				TotalMinus = x.Minus,
				TotalPlus = x.Plus,
				Balance = x.Plus - x.Minus,
			})
			.ToList();
	}

	public async Task<List<MotionTotalSimple>> GetIncomeByCategoriesAsync(
		Guid userId,
		DateTime from,
		DateTime to,
		CancellationToken cancellationToken = default
	)
	{
		var accounts = await GetAccountsWithRateAsync(userId, to, cancellationToken);
		var accountIds = accounts.Select(x => x.Account.Id).ToList();

		var groups = await _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => accountIds.Contains(x.AccountId))
			.Where(x => !x.Item.Category!.IsInternal)
			.GroupBy(x => new
			{
				Id = x.Item.CategoryId,
				Name = x.Item.Category!.Name,
				IsUserCategory = x.Item.Category!.UserId == userId,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.ToListAsync(cancellationToken);

		return groups
			.Select(x => new MotionTotalSimple
			{
				Id = x.Key.IsUserCategory ? x.Key.Id : userId,
				Name = x.Key.Name,
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Amount = x.Sum(a => a.AmountPlus),
			})
			.ToList();
	}

	public Task<List<MotionTotalSimple>> GetIncomeByCategoryAsync(
		Guid userId,
		Guid categoryId,
		DateTime from,
		DateTime to,
		CancellationToken cancellationToken = default
	)
	{
		return _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => x.Item.Category!.UserId == userId)
			.Where(x => x.Item.CategoryId == categoryId)
			.Where(x => !x.Item.Category!.IsInternal)
			.Where(x => x.Item.Category!.UserId == userId)
			.GroupBy(x => new
			{
				Id = x.Item.ItemGlobalId,
				Name = x.Item.ItemGlobal!.Name,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.Select(x => new MotionTotalSimple
			{
				Name = x.Key.Name,
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Amount = x.Sum(a => a.AmountPlus),
			})
			.ToListAsync(cancellationToken);
	}

	public async Task<List<MotionTotalSimple>> GetOutcomeByCategoriesAsync(
		Guid userId,
		DateTime from,
		DateTime to,
		CancellationToken cancellationToken = default
	)
	{
		var accounts = await GetAccountsWithRateAsync(userId, to, cancellationToken);
		var accountIds = accounts.Select(x => x.Account.Id).ToList();

		return await _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => accountIds.Contains(x.AccountId))
			.Where(x => !x.Item.Category!.IsInternal)
			.GroupBy(x => new
			{
				Id = x.Item.CategoryId,
				Name = x.Item.Category!.Name,
				IsUserCategory = x.Item.Category!.UserId == userId,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.Select(x => new MotionTotalSimple
			{
				Id = x.Key.IsUserCategory ? x.Key.Id : userId,
				Name = x.Key.IsUserCategory ? x.Key.Name : "UnCategorized",
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Amount = x.Sum(a => a.AmountMinus),
			})
			.ToListAsync(cancellationToken);
	}

	public async Task<List<MotionTotalSimple>> GetOutcomeByCategoryAsync(
		Guid userId,
		Guid categoryId,
		DateTime from,
		DateTime to,
		CancellationToken cancellationToken = default
	)
	{
		var accounts = await GetAccountsWithRateAsync(userId, to, cancellationToken);
		var accountIds = accounts.Select(x => x.Account.Id).ToList();

		return await _context.Motions
			.Where(x => x.DateTime >= from && x.DateTime <= to)
			.Where(x => accountIds.Contains(x.AccountId))
			.Where(x => !x.Item.Category!.IsInternal)
			.Where(x => x.Item.CategoryId == categoryId)
			.GroupBy(x => new
			{
				Id = x.Item.ItemGlobalId,
				Name = x.Item.ItemGlobal!.Name,
				CurrencyId = x.Account.CurrencyGlobalId,
				CurrencyName = x.Account.CurrencyGlobal!.Name,
			})
			.Select(x => new MotionTotalSimple
			{
				CurrencyId = x.Key.CurrencyId,
				CurrencyName = x.Key.CurrencyName,
				Name = x.Key.Name,
				Amount = x.Sum(a => a.AmountMinus),
			})
			.ToListAsync(cancellationToken);
	}
}