namespace Netina.Repository.Handlers.Newsletters;

public class CreateNewsletterMemberCommandHandler(IRepositoryWrapper repositoryWrapper)
    : IRequestHandler<CreateNewsletterMemberCommand, bool>
{
    public async Task<bool> Handle(CreateNewsletterMemberCommand request, CancellationToken cancellationToken)
    {
        if (request.PhoneNumber.IsNullOrEmpty() && request.Email.IsNullOrEmpty())
            throw new AppException("PhoneNumber and Email is null");
        if (!request.PhoneNumber.IsNullOrEmpty())
        {
            var existedPhoneNumber = await repositoryWrapper.SetRepository<NewsletterMember>()
                .TableNoTracking
                .AnyAsync(c => c.PhoneNumber == request.PhoneNumber, cancellationToken);
            if (existedPhoneNumber == true)
                throw new AppException("PhoneNumber is existed");
        }
        if (!request.Email.IsNullOrEmpty())
        {
            var existedEmail = await repositoryWrapper.SetRepository<NewsletterMember>()
                .TableNoTracking
                .AnyAsync(c => c.Email == request.Email, cancellationToken);
            if (existedEmail == true)
                throw new AppException("Email is existed");
        }

        var ent = NewsletterMember.Create(request.PhoneNumber, request.Email);
        repositoryWrapper.SetRepository<NewsletterMember>()
            .Add(ent);
        await repositoryWrapper.SaveChangesAsync(cancellationToken);
        return true;
    }
}