using CMSMicroservice.Domain.Events;
namespace CMSMicroservice.Application.UserContractCQ.Commands.DeleteUserContract;
public class DeleteUserContractCommandHandler : IRequestHandler<DeleteUserContractCommand, Unit>
{
    private readonly IApplicationDbContext _context;

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

    public async Task<Unit> Handle(DeleteUserContractCommand request, CancellationToken cancellationToken)
    {
        var entity = await _context.UserContracts
            .FirstOrDefaultAsync(x => x.Id == request.Id, cancellationToken) ?? throw new NotFoundException(nameof(UserContract), request.Id);
        entity.IsDeleted = true;
        _context.UserContracts.Update(entity);
        entity.AddDomainEvent(new DeleteUserContractEvent(entity));
        await _context.SaveChangesAsync(cancellationToken);
        return Unit.Value;
    }
}
