namespace MyOffice.Services.Currency;

using AutoMapper;

using Core;
using Core.Extensions;
using Data.Models.Currencies;
using Data.Repositories.Currency;
using Domain;

public class CurrencyService
{
	private readonly ICurrencyGlobalRepository _currencyGlobalRepository;
	private readonly ICurrencyRepository _currencyRepository;
	private readonly ICurrencyRateRepository _currencyRateRepository;
	private readonly IMapper _mapper;

	public CurrencyService(
		ICurrencyGlobalRepository currencyGlobalRepository,
		ICurrencyRepository currencyRepository,
		ICurrencyRateRepository currencyRateRepository,
		IMapper mapper
	)
	{
		_currencyGlobalRepository = currencyGlobalRepository;
		_currencyRepository = currencyRepository;
		_currencyRateRepository = currencyRateRepository;
		_mapper = mapper;
	}

	public List<CurrencyGlobalDto> GetGlobalAll()
	{
		return _mapper.Map<List<CurrencyGlobalDto>>(_currencyGlobalRepository.GetAll());
	}

	public List<CurrencyDto> GetAll(Guid userId)
	{
		return _mapper.Map<List<CurrencyDto>>(_currencyRepository.GetAll(userId));
	}

	public List<CurrencyWithRateDto> GetAllWithRates(Guid userId)
	{
		var list = _currencyRepository.GetAll(userId);

		return list.Select(x => new CurrencyWithRateDto
		{
			Currency = _mapper.Map<CurrencyDto>(x),
			Rate = _mapper.Map<CurrencyRateDto>(_currencyRateRepository.GetLastRates(x.Id).FirstOrDefault()),
		}).ToList();
	}

	public Exec<CurrencyDto, CurrencyAddStatus> CurrencyAdd(Guid userId, CurrencyDto input)
	{
		if (input == null)
			throw new ArgumentNullException(nameof(input));

		var result = new Exec<CurrencyDto, CurrencyAddStatus>(CurrencyAddStatus.success);

		var exists = _currencyRepository.GetByGlobalCurrency(userId, input.CurrencyGlobalId);
		if (exists != null)
		{
			return result.Set(_mapper.Map<CurrencyDto>(exists), CurrencyAddStatus.exists);
		}

		var currency = new Currency
		{
			Id = Guid.NewGuid(),
			UserId = userId,
			CurrencyGlobalId = input.CurrencyGlobalId,
			Name = input.Name,
			ShortName = input.ShortName,
		};

		if (!_currencyRepository.Add(currency))
		{
			return result.Set(CurrencyAddStatus.failed);
		}

		return result.Set(_mapper.Map<CurrencyDto>(currency));
	}

	public Exec<CurrencyDto, CurrencyEditStatus> CurrencyUpdate(
		Guid userId,
		Guid currencyId,
		CurrencyEdit currency
	)
	{
		if (currency == null)
			throw new ArgumentNullException(nameof(currency));

		var result = new Exec<CurrencyDto, CurrencyEditStatus>(CurrencyEditStatus.success);

		var exists = _currencyRepository.Get(userId, currencyId);
		if (exists == null)
		{
			return result.Set(CurrencyEditStatus.not_found);
		}

		exists.Name = currency.Name;
		exists.ShortName = currency.ShortName;
		exists.IsPrimary = currency.IsPrimary;

		if (!_currencyRepository.Update(exists))
		{
			return result.Set(CurrencyEditStatus.failed);
		}

		if (exists.IsPrimary)
		{
			var primaries = _currencyRepository.GetPrimaries(userId);
			foreach (var primary in primaries)
			{
				if (primary.Id != exists.Id)
				{
					primary.IsPrimary = false;
					_currencyRepository.Update(primary);
				}
			}
		}

		return result.Set(_mapper.Map<CurrencyDto>(exists));
	}

	public Exec<CurrencyRateDto, CurrencyAddRateStatus> CurrencyRateAdd(Guid userId, Guid currencyId, CurrencyRateDto input)
	{
		if (input == null)
			throw new ArgumentNullException(nameof(input));

		var result = new Exec<CurrencyRateDto, CurrencyAddRateStatus>(CurrencyAddRateStatus.success);

		var currency = _currencyRepository.Get(userId, currencyId);
		if (currency == null)
		{
			return result.Set(CurrencyAddRateStatus.not_found);
		}

		var currencyRate = new CurrencyRate
		{
			CurrencyId = currency.Id,
			DateTime = input.DateTime.Date,
			Rate = input.Rate,
			Quantity = input.Quantity,
		};

		var rates = _currencyRateRepository.GetAtDate(currencyRate.CurrencyId, currencyRate.DateTime);
		var rate = rates.Find(x => x.Rate == currencyRate.Rate);

		if (rate == null)
		{
			if (!_currencyRateRepository.AddRate(currencyRate))
			{
				return result.Set(CurrencyAddRateStatus.failed);
			}

			// TODO: more logic to fix current rate
			if (currencyRate.DateTime.Date == DateTime.UtcNow.Date || !currency.CurrentRateId.HasValue)
			{
				currency.CurrencyGlobal = null;
				currency.CurrentRateId = currencyRate.Id;
				_currencyRepository.Update(currency);
			}
		}

		return result.Set(_mapper.Map<CurrencyRateDto>(rate));
	}

	public Exec<CurrencyDto, GeneralExecStatus> Remove(Guid userId, Guid id)
	{
		var result = new Exec<CurrencyDto, GeneralExecStatus>(GeneralExecStatus.success);

		var currency = _currencyRepository.Get(userId, id);
		if (currency == null)
		{
			return result.Set(GeneralExecStatus.not_found);
		}

		if (!_currencyRepository.Remove(currency))
		{
			return result.Set(GeneralExecStatus.failure);
		}

		return result.Set(_mapper.Map<CurrencyDto>(currency));
	}
}
