using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.CreateNewUserAddress;
public class CreateNewUserAddressCommandHandler : IRequestHandler<CreateNewUserAddressCommand, CreateNewUserAddressResponseDto>
{
    private readonly IApplicationDbContext _context;

    public CreateNewUserAddressCommandHandler(IApplicationDbContext context)
    {
        _context = context;
    }

    public async Task<CreateNewUserAddressResponseDto> Handle(CreateNewUserAddressCommand request,
        CancellationToken cancellationToken)
    {
        var entity = request.Adapt<UserAddress>();
        if (!await _context.UserAddresses.AnyAsync(x => x.UserId == request.UserId, cancellationToken: cancellationToken))
            entity.IsDefault = true;
        await _context.UserAddresses.AddAsync(entity, cancellationToken);
        entity.AddDomainEvent(new CreateNewUserAddressEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return entity.Adapt<CreateNewUserAddressResponseDto>();
    }
}
