namespace MyOffice.Data.Repositories.Currency;

using Microsoft.EntityFrameworkCore;
using Models.Currencies;
using MyOffice.Data.Repositories;
using MyOffice.DbContext;

public class CurrencyRepository : AppRepository<Currency>, ICurrencyRepository
{
	public CurrencyRepository(AppDbContext context) : base(context)
	{
	}

	public List<Currency> GetAll(Guid userId)
	{
		return _context.Currencies
			.Include(x => x.CurrencyGlobal)
			.Where(x => x.UserId == userId)
			.ToList();
	}

	public async Task<List<Currency>> GetAllAsync(Guid userId, CancellationToken cancellationToken = default)
	{
		return await _context.Currencies
			.Include(x => x.CurrencyGlobal)
			.Where(x => x.UserId == userId)
			.ToListAsync(cancellationToken);
	}

	public Currency? Get(Guid userId, Guid id)
	{
		return _context
			.Currencies
			.Include(x => x.CurrencyGlobal)
			.FirstOrDefault(x => x.Id == id && x.UserId == userId);
	}

	public async Task<Currency?> GetAsync(Guid userId, Guid id, CancellationToken cancellationToken = default)
	{
		return await _context
			.Currencies
			.Include(x => x.CurrencyGlobal)
			.FirstOrDefaultAsync(x => x.Id == id && x.UserId == userId, cancellationToken);
	}

	public Currency? GetByGlobalCurrency(Guid userId, string globalCurrencyId)
	{
		return _context.Currencies.FirstOrDefault(x => x.UserId == userId && x.CurrencyGlobalId == globalCurrencyId);
	}

	public async Task<Currency?> GetByGlobalCurrencyAsync(
		Guid userId,
		string globalCurrencyId,
		CancellationToken cancellationToken = default)
	{
		return await _context.Currencies.FirstOrDefaultAsync(
			x => x.UserId == userId && x.CurrencyGlobalId == globalCurrencyId,
			cancellationToken);
	}

	public bool Add(Currency currency)
	{
		return AddBase(currency) > 0;
	}

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

	public bool Update(Currency currency)
	{
		return UpdateBase(currency) > 0;
	}

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

	public bool Remove(Currency currency)
	{
		return RemoveBase(currency) > 0;
	}

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

	public List<Currency> GetPrimaries(Guid userId)
	{
		return _context.Currencies.Where(x => x.UserId == userId && x.IsPrimary).ToList();
	}

	public async Task<List<Currency>> GetPrimariesAsync(Guid userId, CancellationToken cancellationToken = default)
	{
		return await _context.Currencies
			.Where(x => x.UserId == userId && x.IsPrimary)
			.ToListAsync(cancellationToken);
	}
}
