namespace MyOffice.Data.Repositories.Account;

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

public class AccountAccessInviteRepository : AppRepository<AccountAccessInvite>, IAccountAccessInviteRepository
{
	public AccountAccessInviteRepository(AppDbContext context) : base(context)
	{
	}

	public AccountAccessInvite? Get(Guid userId, string email)
	{
		return _context.AccountAccessInvites
			.FirstOrDefault(x => x.UserId == userId
							 && x.Email == email
							 && !x.AcceptedOn.HasValue
							 && !x.RejectedOn.HasValue
							 );
	}

	public async Task<AccountAccessInvite?> GetAsync(Guid userId, string email, CancellationToken cancellationToken = default)
	{
		return await _context.AccountAccessInvites
			.FirstOrDefaultAsync(x => x.UserId == userId
							 && x.Email == email
							 && !x.AcceptedOn.HasValue
							 && !x.RejectedOn.HasValue,
							 cancellationToken);
	}

	public bool Add(AccountAccessInvite invite)
	{
		return AddBase(invite) > 0;
	}

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

	public bool Update(AccountAccessInvite invite)
	{
		return UpdateBase(invite) > 0;
	}

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

	public IEnumerable<AccountAccessInvite> GetActive(string email)
	{
		return _context
			.AccountAccessInvites
			.Include(x => x.Account)
			.Where(x => x.Email == email && !x.AcceptedOn.HasValue && !x.RejectedOn.HasValue);

	}

	public async Task<List<AccountAccessInvite>> GetActiveAsync(string email, CancellationToken cancellationToken = default)
	{
		return await _context
			.AccountAccessInvites
			.Include(x => x.Account)
			.Where(x => x.Email == email && !x.AcceptedOn.HasValue && !x.RejectedOn.HasValue)
			.ToListAsync(cancellationToken);
	}

	public AccountAccessInvite? Get(Guid id)
	{
		return _context.AccountAccessInvites.FirstOrDefault(x => x.Id == id);
	}

	public async Task<AccountAccessInvite?> GetAsync(Guid id, CancellationToken cancellationToken = default)
	{
		return await _context.AccountAccessInvites.FirstOrDefaultAsync(x => x.Id == id, cancellationToken);
	}
}