namespace MyOffice.Services.Dashboard;

using MyOffice.Services.Dashboard.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Core.Extensions;
using Data.Repositories.Account;
using Data.Repositories.Currency;
using MyOffice.Data.Models.Accounts;

public class DashboardService
{
	private readonly IAccountRepository _accountRepository;
	private readonly ICurrencyRateRepository _currencyRateRepository;

	public DashboardService(
		IAccountRepository accountRepository,
		ICurrencyRateRepository currencyRateRepository
	)
	{
		_accountRepository = accountRepository;
		_currencyRateRepository = currencyRateRepository;
	}

	public DashboardData GetDashboardRestData(Guid userId)
	{
		var rests = _accountRepository.GetRestAtDate(userId, DateTime.UtcNow);

		var result = new DashboardData
		{
			Balance = rests
				.Where(x => (x.Type == AccountAccessTypeEnum.balance || x.Type == AccountAccessTypeEnum.credit) && x.CurrencyRate.HasValue)
				.Sum(x => x.Balance * (x.CurrencyRate * x.CurrencyQuantity)),
			
			BalanceDebit = rests
				.Where(x => x.Type == AccountAccessTypeEnum.balance && x.CurrencyRate.HasValue)
				.Sum(x => x.Balance * (x.CurrencyRate * x.CurrencyQuantity)),
			
			BalanceCredit = rests
				.Where(x => x.Type == AccountAccessTypeEnum.credit && x.CurrencyRate.HasValue)
				.Sum(x => x.Balance * (x.CurrencyRate * x.CurrencyQuantity)),

			BalanceRests = rests
				.Where(x => x.Type == AccountAccessTypeEnum.balance)
				.Where(x => x.CurrencyRate.HasValue && x.Balance.HasValue && x.Balance != 0)
				.Select(x => new DashboardRestData
				{
					Id = x.Id,
					Name = x.Name,
					Balance = x.Balance,
					CurrencyName = x.CurrencyName,
					CurrencyShortName = x.CurrencyShortName,
					CurrencyRate = x.CurrencyRate,
					CurrencyQuantity = x.CurrencyQuantity,
				})
				.OrderByDescending(x => x.BalanceAtRate)
				.ToList(),
		};

		return result;
	}
}
