using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserAddressCQ.Commands.SetAddressAsDefault;
public class SetAddressAsDefaultCommandHandler : IRequestHandler<SetAddressAsDefaultCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(SetAddressAsDefaultCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.UserAddresses
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(UserAddress), request.Id);

        var entities = await _context.UserAddresses
            .Where(x => x.UserId == entity.UserId)
            .ToListAsync(cancellationToken);
        entities.ForEach(x => x.IsDefault = false);
        await _context.SaveChangesAsync(cancellationToken);

        entity.IsDefault = true;
        _context.UserAddresses.Update(entity);
        entity.AddDomainEvent(new SetAddressAsDefaultEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
