using Microsoft.EntityFrameworkCore;
using Microsoft.IdentityModel.Tokens;

namespace Netina.Repository.Handlers.Newsletters;

public class CreateNewsletterMemberCommandHandler : IRequestHandler<CreateNewsletterMemberCommand,bool>
{
    private readonly IRepositoryWrapper _repositoryWrapper;

    public CreateNewsletterMemberCommandHandler(IRepositoryWrapper repositoryWrapper)
    {
        _repositoryWrapper = repositoryWrapper;
    }
    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;
    }
}